Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

subquery - SQL Subselect calculated in one row

I have a trouble getting an SQL select to work.

I have one table - below is the example:

|id|name  |hits|
|1 |peter | 6  |
|2 |john  | 13 |
|3 |max   | 12 |
|4 |foo   | 8  |
|5 |bar   | 4  |

I want to calculate the sum of every entry under 10 hits and every entry over 10 hits in one output.

Like below:

|sum-over-10|sum-under-10|
| 25        | 18         |

I tried inner join and outer join but I think that's the wrong approach. If I do a subselect it always filters by the main select.

Don't know how to start here :-) Will be glad and thankful for any advice!

question from:https://stackoverflow.com/questions/65872827/sql-subselect-calculated-in-one-row

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just use conditional aggregation:

select sum(case when hits < 10 then hits else 0 end),
       sum(case when hits > 10 then hits else 0 end)
from t;

Note: The results do not include rows where hits = 10. You might want <= or >= if you want to include these.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...