aggregate-filter

SQL count if columns

丶灬走出姿态 提交于 2019-12-28 14:29:48
问题 What is the best way to create columns which count the number of occurrences of data in a table? The table needs to be grouped by one column. I have seen SELECT sum(CASE WHEN question1 = 0 THEN 1 ELSE 0 END) AS ZERO, sum(CASE WHEN question1 = 1 THEN 1 ELSE 0 END) AS ONE, sum(CASE WHEN question1 = 2 THEN 1 ELSE 0 END) AS TWO, category FROM reviews GROUP BY category where question1 can have a value of either 0, 1 or 2. I have also seen a version of that using count(CASE WHEN question1 = 0 THEN

Select multiple row values into single row with multi-table clauses

旧巷老猫 提交于 2019-12-14 03:59:51
问题 I've searched the forums and while I see similar posts, they only address pieces of the full query I need to formulate (array_aggr, where exists, joins, etc.). If the question I'm posting has been answered, I will gladly accept references to those threads. I did find this thread ...which is very similar to what I need, except it is for MySQL, and I kept running into errors trying to get it into psql syntax. Hoping someone can help me get everything together. Here's the scenario: Attribute

Calculate the sum of a field filtered by a window defined on another field

两盒软妹~` 提交于 2019-12-12 04:56:14
问题 I have table event : event_date, num_events, site_id I can easily use aggregate SQL to do SELECT SUM(num_events) GROUP BY site_id . But I also have another table site : site_id, target_date I'd like to do a JOIN, showing the SUM of num_events within 60 days of the target_date , 90 days, 120 days, etc. I thought this could easily be done using a WHERE clause in the aggregate SQL. However, this is complicated by two challenges: The target_date is not fixed, but varies for each site_id I'd like

Postgres COUNT number of column values with INNER JOIN

∥☆過路亽.° 提交于 2019-12-01 06:25:44
问题 I am creating a report in Postgres 9.3. This is my SQL Fiddle. Basically I have two tables, responses and questions , the structure is: responses ->id ->question_id ->response questions ->id ->question ->costperlead for the column response there can only be 3 values, Yes/No/Possbily , and my report should have the columns: question_id , # of Yes Responses , # of No Responses , # of Possbily Responses , Revenue Then: # of Yes Responses - count of all Yes values in the response column # of No

How can I simplify this game statistics query?

谁说胖子不能爱 提交于 2019-11-26 00:19:41
问题 This code works as expected, but I it\'s long and creepy. select p.name, p.played, w.won, l.lost from (select users.name, count(games.name) as played from users inner join games on games.player_1_id = users.id where games.winner_id > 0 group by users.name union select users.name, count(games.name) as played from users inner join games on games.player_2_id = users.id where games.winner_id > 0 group by users.name) as p inner join (select users.name, count(games.name) as won from users inner