是否可以从查询中转动输出?

时间:2014-11-21 09:08:09

标签: mysql sql pivot on-the-fly

我有这个查询的输出:

select Date,Status, count(distinct persons)from TableA where Date='2014-11-04' group by Status;

+------------+------------------------+-------------------------------+
| Date       | Status                 | count(distinct persons)       |
+------------+------------------------+-------------------------------+
| 2014-11-04 | 0                      |                            45 |
| 2014-11-04 | 1                      |                            93 |
+------------+------------------------+-------------------------------+

我想得到的是:

+------------+------------------------+-------------------------------+
| Date       | 0                      |     1                         |
+------------+------------------------+-------------------------------+
| 2014-11-04 | 45                     |    93                         |
+------------+------------------------+-------------------------------+

2 个答案:

答案 0 :(得分:3)

您可以使用COUNT

CASE函数中添加条件
SELECT  Date,
        COUNT(DISTINCT CASE WHEN status = 0 THEN persons END) AS `0`,
        COUNT(DISTINCT CASE WHEN status = 1 THEN persons END) AS `1`
FROM    TableA
WHERE   Date = '2014-11-04'
GROUP BY Date;

答案 1 :(得分:-1)

您可以使用以下代码 -

select Date, [0], [1]
from
(select Date,Status,persons
from TableA 
where Date='2014-11-04') AS SourceTable
PIVOT
(
    COUNT(persons)
    FOR Status IN ([0],[1])
) AS PivotTable;
相关问题