Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...