如何使用某些条件创建别名sql查询

时间:2016-03-15 04:20:39

标签: mysql

我写过这样的SQL查询:

SELECT `petugas_input`, 
COUNT(`petugas_input`) AS `01-MAR`,
COUNT(`petugas_input`) AS `02-MAR`,
COUNT(`petugas_input`) AS `03-MAR`
FROM `tabel_arsip`
WHERE `tgl_input_arsip`>='2016-03-01 00:00:00' AND `tgl_input_arsip`<='2016-03-01 23:59:59'
GROUP BY `petugas_input`

及其生成结果

sample_table

我的问题是如何将标准添加到别名列,以便它在不同的日期显示不同的值。 (与上述日期列中的值不同)

3 个答案:

答案 0 :(得分:1)

你必须依赖一些复杂的分组:

SELECT 
    `petugas_input`, 
    SUM(CASE WHEN DATE(tgl_input_arsip) = '2016-03-01' THEN 1 ELSE 0 END) AS `01-MAR`, 
    SUM(CASE WHEN DATE(tgl_input_arsip) = '2016-03-02' THEN 1 ELSE 0 END) AS `02-MAR`, 
    SUM(CASE WHEN DATE(tgl_input_arsip) = '2016-03-03' THEN 1 ELSE 0 END) AS `03-MAR`,
FROM `tabel_arsip`
WHERE `tgl_input_arsip`>='2016-03-01 00:00:00' AND `tgl_input_arsip`<='2016-03-01 23:59:59'
GROUP BY `petugas_input`

答案 1 :(得分:0)

您不应该考虑使用这些硬编码的列别名而是针对每个petugas_input以及每个date (在给定日期范围内)以及计数。

这样的事情:

SELECT 
`petugas_input`, 
DATE(`tgl_input_arsip`) `date`,
COUNT(*) total
FROM `tabel_arsip`
WHERE `tgl_input_arsip`>='2016-03-01 00:00:00' AND `tgl_input_arsip`<='2016-03-01 23:59:59'
GROUP BY `petugas_input`,`date`;

您将获得以下输出结构:

petugas_input           date               total

A                    yyyy-mm-dd             n1
B                    yyyy-mm-dd             n2

答案 2 :(得分:0)

试试这个:

SELECT `petugas_input`, 
COUNT(CASE WHEN DATE(tgl_input_arsip) = '2016-03-01' THEN petugas_input ELSE 0 END) AS `01-MAR`, 
COUNT(CASE WHEN DATE(tgl_input_arsip) = '2016-03-02' THEN petugas_input  ELSE 0 END) AS `02-MAR`, 
COUNT(CASE WHEN DATE(tgl_input_arsip) = '2016-03-03' THEN petugas_input ELSE 0 END) AS `03-MAR`
FROM `tabel_arsip`
WHERE `tgl_input_arsip`>='2016-03-01 00:00:00' AND `tgl_input_arsip`<='2016-03-03 23:59:59'
GROUP BY `petugas_input`;

:)