简体   繁体   中英

trouble GROUPing rows in postgres

I have a table myTable

id  | test_id_1 | test_id_2  
001 | 0         | 1  
001 | 1         | 0  
002 | 1         | 0  
002 | 0         | 1  
003 | 1         | 0  
003 | 0         | 1

And I'm trying to group the rows based on id so that I can get single rows with the id like such

 id | test_id_1 | test_id_2  
001 | 1         | 1    
002 | 1         | 1    
003 | 1         | 1  

This is my query

SELECT *
FROM myTable
GROUP BY id

I keep getting an error saying that test_id_1 is not in the GROUP BY . But if I do include it I don't get the table I am looking for.

Try this (I assume what you need is the sum of test_id_1 and test_id_2):

SELECT id, SUM(TEST_ID_1), SUM(TEST_ID_2)
FROM myTable
GROUP BY id

The group by syntax requires you to aggregate all the columns are not listed in "group by" clause, and that is the reason you got error. By speaking of aggregation, you can use SUM, COUNT, MAX OR MIN functions.

You can also get the same output, while you go for maximum value of test_id_1 and test_id_2 for each id wise group. So you can try the below query also

SELECT id, MAX(TEST_ID_1), MAX(TEST_ID_2)
FROM myTable
GROUP BY id

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