简体   繁体   中英

SQL query to get only rows match the condition based on two separated columns under one 'group by'

The simple SELECT query would return the data as below:

Select ID, User, Country, TimeLogged from Data

ID     User      Country   TimeLogged
1      Samantha  SCO       10
1      John      UK         5
1      Andrew    NZL       15
2      John      UK        20
3      Mark      UK        10
3      Mark      UK        20
3      Steven    UK        10
3      Andrew    NZL       15
3      Sharon    IRL        5
4      Andrew    NZL       25
4      Michael   AUS        5
5      Jessica   USA       30

I would like to return a sum of time logged for each user grouped by ID But for only ID numbers where both of these values Country = UK and User = Andrew are included within their rows.

So the output in the above example would be

ID     User      Country   TimeLogged
1      John      UK         5
1      Andrew    NZL       15
3      Mark      UK        30
3      Steven    UK        10
3      Andrew    NZL       15

First you need to identify which IDs you're going to be returning

SELECT ID FROM MyTable WHERE Country='UK' 
INTERSECT
SELECT ID FROM MyTable WHERE [User]='Andrew';

and based on that, you can then filter to aggregate the expected rows.

SELECT ID, 
       [User], 
       Country, 
       SUM(Timelogged) as Timelogged 
FROM mytable
WHERE (Country='UK' OR [User]='Andrew')
AND ID IN(  SELECT ID FROM MyTable WHERE Country='UK' 
            INTERSECT
            SELECT ID FROM MyTable WHERE [User]='Andrew')
GROUP BY ID, [User], country;

So, you have described what you need to write almost perfectly but not quite. Your result table indicates that you want Country = UK OR User = Andrew, rather than AND

You need to select and group by, then include a WHERE:-

Select ID, User, Country, SUM(Timelogged) as Timelogged from mytable
WHERE Country='UK' OR User='Andrew'
Group by ID, user, country

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM