8

I have this mysql table:

DATE | VALUE

and I wish to become a select which shows me this information as:

DATE | COUNT TOTAL | COUNT VAL=1 | COUNT VAL=2

Any ideas how I can achieve this?

3
  • This sounds like a homework assignment. You should add that tag, and then post what you've tried so far, explain what didn't work as you expected, and then we can try and help you figure out why. We're not going to do the work for you, because you won't learn anything that way. Commented Sep 9, 2011 at 20:50
  • Well I can create seperate queries (one for a total overview, one for VAL1 and VAL2). But I can't get them combined: SELECT date, COUNT(*) FROM payments WHERE paymentProviderId = 2 GROUP BY YEAR( DATE ) , MONTH(DATE ) , DAY(DATE ) (and no it's not a homework assignment) Commented Sep 9, 2011 at 20:50
  • I have this exact question right now, and it is not homework in my case. Commented Jan 31, 2018 at 12:04

3 Answers 3

16
SELECT date,
       COUNT(*),
       COUNT( IF( value = 1, 1, NULL ) ),
       COUNT( IF( value = 2, 1, NULL ) )
FROM my_table
Sign up to request clarification or add additional context in comments.

1 Comment

Is there any neater way? Not including the hardcorded value.
2

I think with SUM() you can get neater code. Since it sums the values respective expression for row.

SELECT date,
   COUNT(*),
   SUM( value = 1 ),
   SUM( value = 2 )
FROM my_table

Official Documentation can be found here.

1 Comment

Thats the more cleaner way i guess
0
SELECT `date`, COUNT(*) AS `COUNT TOTAL`, 
  COUNT(CASE `value` WHEN 1 THEN `value` END) AS `COUNT VAL=1`
  COUNT(CASE `value` WHEN 2 THEN `value` END) AS `COUNT VAL=2`
FROM mytable
GROUP BY `date`

The CASE expressions will be null when there is no match. Nulls are not counted by COUNT().

I imagine you might want a dynamic number of columns, one column for each value found in the data. This is not possible in SQL. The columns must be known at the time you write the query.

So you have two options to get subtotals per value:

  • First query the distinct values from all rows of value and construct an SQL query dynamically, appending one column in the select-list for each distinct value you want to report. Then run this SQL query.

  • Alternatively, fetch all the rows as rows. Count the subtotals per value in application code.

One further alternative is to count subtotals by groups, and include totals:

SELECT `value`, `date, COUNT(*) AS `COUNT SUBTOTAL`
FROM mytable
GROUP BY `value`, `date` WITH ROLLUP

But that doesn't report the subtotals in columns as you requested, it reports the subtotals in rows.

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.