简体   繁体   中英

SQL count value per day return error

I have this dataset

dia valor valor_b
=== ===== =======
1    1     b1
1    2     b2
1    1     b3
1    2     b3
2    1     b2
2    3     b1
2    1     b1
2    1     b1
2    1     b2
1    3     b3
5    1     b4
5    3     b1

I need count how many times appear valor_b per day. And show in this structure:

valor dia_1 dia_2 dia_3 dia_4 dia_5
===== ===== ===== ===== ===== =====
1     2     4     0     0     1
2     2     0     0     0     0
3     1     1     0     0     1

First time i do this to show the value_b

SELECT valor, 
  group_concat(DISTINCT IF(dia=1, valor_b, NULL)) dia_1,
  group_concat(DISTINCT IF(dia=2, valor_b, NULL)) dia_2,
  group_concat(DISTINCT IF(dia=3, valor_b, NULL)) dia_3,
  group_concat(DISTINCT IF(dia=4, valor_b, NULL)) dia_4,
  group_concat(DISTINCT IF(dia=5, valor_b, NULL)) dia_5
FROM test
GROUP BY valor;

But now counting valor_b phpmyadmin returns this error

1111 - Invalid use of group function

And this is the used sentence

SELECT valor, 
      group_concat(DISTINCT IF(dia=1, count(valor_b), NULL)) dia_1,
      group_concat(DISTINCT IF(dia=2, count(valor_b), NULL)) dia_2,
      group_concat(DISTINCT IF(dia=3, count(valor_b), NULL)) dia_3,
      group_concat(DISTINCT IF(dia=4, count(valor_b), NULL)) dia_4,
      group_concat(DISTINCT IF(dia=5, count(valor_b), NULL)) dia_5
    FROM test
    GROUP BY valor;

I see no concatenated strings in your results. So why use GROUP_CONCAT at all? Don't you simply want:

select
  valor,
  sum(dia = 1) as dia_1,
  sum(dia = 2) as dia_2,
  sum(dia = 3) as dia_3,
  sum(dia = 4) as dia_4,
  sum(dia = 5) as dia_5
from test
group by valor
order by valor;

This makes use of true = 1 and false = 0 in MySQL.

I am not sure what "I need count how many times appear valor_b per day" is supposed to mean exactly. Count records where valor_b is not null? Then you'd have to add this to the expression:

  sum(dia = 1 and valor_b is not null) as dia_1,

etc.

If I get you correct

SELECT valor, 
      sum(IF(dia=1, 1, NULL)) dia_1,
      sum(IF(dia=2, 1, NULL)) dia_2,
      sum(IF(dia=3, 1, NULL)) dia_3,
      sum(IF(dia=4, 1, NULL)) dia_4,
      sum(IF(dia=5, 1, NULL)) dia_5
    FROM test
    GROUP BY valor;

You don't need the group_concat here, a sum alone should suffice

SELECT  valor, 
        sum(IF(dia=1, 1, 0)) dia_1,
        sum(IF(dia=2, 1, 0)) dia_2,
        sum(IF(dia=3, 1, 0)) dia_3,
        sum(IF(dia=4, 1, 0)) dia_4,
        sum(IF(dia=5, 1, 0)) dia_5
FROM    test
GROUP BY valor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM