Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should my query be?

I have a table like this:

    date,               flag
    22/05/13             1
    22/05/13             1
    22/05/13             0
    23/05/13             1
    23/05/13             0

So I need a query where I count in different columns the 2 possible values of flag.

    date       flag1        flag0
    22/05/13    2            1
    23/05/13    1            1

How should I write my query in order to get the data in the way I showed above?

like image 819
linker85 Avatar asked May 05 '26 05:05

linker85


2 Answers

Something like this:

SELECT
    [date]
    SUM(CASE WHEN tbl.flag=0 THEN 1 ELSE 0 END) AS flag0,
    SUM(CASE WHEN tbl.flag=1 THEN 1 ELSE 0 END) AS flag1
FROM
    tbl
GROUP BY
    tbl.[date]
like image 80
Arion Avatar answered May 06 '26 18:05

Arion


SELECT [date], sum(flag) "flag1", sum(1-flag) "flag0"
FROM [table]
GROUP BY [date]

Normally I'd use a case statement inside the SUM() functions, but in this case it works out that we can get away with simple (and faster) expressions.

like image 29
Joel Coehoorn Avatar answered May 06 '26 17:05

Joel Coehoorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!