0

I have the table in PostgreSQL DB

enter image description here

Need to calculate SUM of counts for each event_type (example for 4 and 1) When I use query like this

SELECT account_id, date,
  CASE
    WHEN event_type = 1 THEN SUM(count)
    ELSE null
  END AS shows,
  CASE
    WHEN event_type = 4 THEN SUM(count)
    ELSE null
  END AS clicks
FROM widgetstatdaily WHERE account_id = 272 AND event_type = 1 OR event_type = 4 GROUP BY account_id, date, event_type ORDER BY date

I receive this table

enter image description here

With <null> fields. It's because I have event_type in select and I need to GROUP BY on it.

How I can make query to receive grouped by account_id and date result without null's in cells? Like (first row)

272   2018-03-28 00:00:00.000000    57    2

May be I can group it after receiving result

2 Answers 2

2

You need conditional aggregation and some other fixes. Try this:

SELECT account_id, date,
       SUM(CASE WHEN event_type = 1 THEN count END) as shows,
       SUM(CASE WHEN event_type = 4 THEN count END) as clicks
FROM widgetstatdaily
WHERE account_id = 272 AND
      event_type IN (1, 4)
GROUP BY account_id, date
ORDER BY date;

Notes:

  • The CASE expression should be an argument to the SUM().
  • The ELSE NULL is redundant. The default without an ELSE is NULL.
  • The logic in the WHERE clause is probably not what you intend. That is fixed using IN.
Sign up to request clarification or add additional context in comments.

1 Comment

Unreal Gordon. Our answers were even almost formatted the same way. You must get carpal tunnel regularly :-)
1

try its

SELECT account_id, date,
       SUM(CASE WHEN event_type = 1 THEN count  else 0 END) as shows,
       SUM(CASE WHEN event_type = 4 THEN count  else 0 END) as clicks
FROM widgetstatdaily
WHERE account_id = 272 AND
      event_type IN (1, 4)
GROUP BY account_id, date
ORDER BY date;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.