I would like to group by Company & Date and generate count columns for 2 separate values (Flag=Y and Flag=N). Input table looks like this:
Company Date Flag
------- ------- -----
001 201201 Y
001 201201 N
001 201202 N
001 201202 N
001 201202 Y
The output should look like this:
Company Date Count_Y Count_N
------- ------ ------- -------
001 201201 1 1
001 201202 1 2
How can I write the SQL query? Any kind of help is appreciated! Thanks!
If you have an identifier/key for this table, then you can pivot it like this:
Where
ID
is your identifier for the tableCompany
.Fiddle with the code here
If you do not have an identifier/key for the table and Company, Date and Flag are the only columns you have, then you can do a
PIVOT
on the count of theFlag
itself like @ConradFrix has suggested in the comments:You can do it using correlated subqueries like this:
You can also do it more concisely, but perhaps with (arguably) slighly less readability using the
SUM
trick:In Oracle/PLSQL, the
DECODE
function can be used to replace theCASE
for the even more concise: