我正在尝试做一些与之前问过的问题非常类似的事情,但我似乎无法让它正常工作。这是我之前的问题:How to get totals per day
表格如下:
Table Name: Totals
Date |Program label |count
| |
2013-04-09 |Salary Day |4364
2013-04-09 |Monthly |6231
2013-04-09 |Policy |3523
2013-04-09 |Worst Record |1423
2013-04-10 |Salary Day |9872
2013-04-10 |Monthly |6543
2013-04-10 |Policy |5324
2013-04-10 |Worst Record |5432
2013-04-10 |Salary Day |1245
2013-04-10 |Monthly |6345
2013-04-10 |Policy |5431
2013-04-10 |Worst Record |5232
我的问题是:使用MSSQL 2008 - 有没有办法让我获得当前每月每个程序标签的总计数。正如您所看到的,它有时会每天运行两次。我需要能够解释这一点。
输出应如下所示:
Date |Salary Day |Monthly |Policy |Worst Record
2013-04-9 |23456 |63241 |23521 |23524
2013-04-10|45321 |72535 |12435 |83612
答案 0 :(得分:8)
使用PIVOT
表格运算符,如下所示:
SELECT *
FROM Totals AS t
PIVOT
(
SUM(count)
FOR [Program label] IN ([Salary Day],
[Monthly],
[Policy],
[Worst Record])
) AS p;
看到它的实际效果:
这会给你:
| DATE | SALARY DAY | MONTHLY | POLICY | WORST RECORD |
-------------------------------------------------------------
| 2013-04-09 | 4364 | 6231 | 3523 | 1423 |
| 2013-04-10 | 11117 | 12888 | 10755 | 10664 |
答案 1 :(得分:3)
试试这个
select Date,
sum(case when [Program label] = 'Salary Day' then count else 0 end) [Salary Day],
sum(case when [Program label] = 'Monthly' then count else 0 end) [Monthly],
sum(case when [Program label] = 'Policy' then count else 0 end) [Policy],
sum(case when [Program label] = 'Worst Record' then count else 0 end) [Worst Record]
from Totals Group by [Date];
答案 2 :(得分:2)
试试这个 -
SELECT
date
, [Salary Day] = SUM(CASE when [Program label] = 'Salary Day' then COUNT end)
, [Monthly] = SUM(CASE when [Program label] = 'Monthly' then COUNT end)
, [Policy] = SUM(CASE when [Program label] = 'Policy' then COUNT end)
, [Worst Record] = SUM(CASE when [Program label] = 'Worst Record' then COUNT end)
FROM Totals
GROUP BY [Date];