简体   繁体   English

MySql:按日期计数值的出现

[英]MySql: Count occurrences of values by date

I'm trying to count the number of occurences based severity level (1-5) on distinct dates. 我正在尝试计算不同日期基于严重性级别(1-5)的发生次数。 Note I have another table but severity levels are words (High, Medium and Low...not 1 to 5). 请注意,我有另一个表,但是严重性级别是单词(高,中和低...不是1到5)。

Example of DB: 数据库示例:

DATE          LEVEL    COUNT
----          -----    -----
05/11/2018    3        14
05/11/2018    5        11
05/11/2018    5        11
05/12/2018    3        14
05/12/2018    2        14
05/13/2018    2        11
05/13/2018    1        12

Expected output 预期产量

 Date        1    2   3   4   5
 ---------   --   --  --  --  --
 05/11/2018  0    0   14  0   22
 05/12/2018  0    14  14  0   0
 05/13/2018  12   11  0   0   0

Expected output 2 预期产量2

 Level        05/11/2018   05/12/2018  05/13/2018
 ---------    ----------   ----------  ----------
 1               0             0           12       
 2               0             14          11
 3               14            14          0
 4               0             0           0
 5               22            0           0

I tried 我试过了

SELECT CONCAT(DAY(`DATE`) ,MONTH(`DATE`) , YEAR(`DATE`)) AS DDMMYYYY , 
 COUNT(DISTINCT LEVEL) as NumCount
FROM  `myDatabase` 
GROUP BY CONCAT(DAY(`DATE`),MONTH(`DATE`), YEAR(`DATE`) )

but I'm getting the number of different counts.. 但我得到了不同数量的数量。

Any guidance would be appreciated! 任何指导将不胜感激! Thx! 谢谢!

You can't really do pivot tables in MySQL. 您实际上无法在MySQL中执行数据透视表。 However with a fixed number of columns (such as expected output #1) you can simulate them with CASE statements eg 但是,对于固定数量的列(例如预期的输出#1),您可以使用CASE语句模拟它们,例如

select date_format(date, '%d%m%Y') as Date,
   sum(case when level=1 then count else 0 end) as `1`,
   sum(case when level=2 then count else 0 end) as `2`,
   sum(case when level=3 then count else 0 end) as `3`,
   sum(case when level=4 then count else 0 end) as `4`,
   sum(case when level=5 then count else 0 end) as `5`
from table1
group by Date

Output: 输出:

Date        1   2   3   4   5
11052018    0   0   14  0   22
12052018    0   14  14  0   0
13052018    12  11  0   0   0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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