我陷入了一个难题,无法按日期获取多个员工的多个产品数据,这不知道如何解决。
主表/表1-在此数量中,常数始终为1
SNo | EmpName | LblCode | DateOfSour | ProdType | Amount
1 | Emp1 | 001 | 2019-01-01 | Prod1 | 1
2 | Emp1 | 001 | 2019-01-01 | Prod2 | 1
3 | Emp2 | 002 | 2019-01-02 | Prod1 | 1
4 | Emp1 | 001 | 2019-01-01 | Prod1 | 1
5 | Emp3 | 003 | 2019-01-01 | Prod2 | 1
6 | Emp2 | 002 | 2019-01-03 | Prod2 | 1
欲望的结果
EmpName |DateOfSour| LblCode | Prod1 | Prod2 | Prod3 |DateOfSour| Prod1 | Prod2 | Prod3 |DateOfSour| Prod1 | Prod2 | Prod3 |
Emp1 |2019-01-01| 001 | 2 | 1 | 0 |2019-01-02| 0 | 0 | 0 |2019-01-03| 0 | 0 | 0 |
Emp2 |2019-01-01| 002 | 0 | 0 | 0 |2019-01-02| 1 | 0 | 0 |2019-01-03| 0 | 1 | 0 |
Emp3 |2019-01-01| 003 | 0 | 1 | 0 |2019-01-02| 0 | 0 | 0 |2019-01-03| 0 | 0 | 0 |
Total |2019-01-01| | 2 | 2 | 0 |2019-01-02| 1 | 0 | 0 |2019-01-03| 0 | 1 | 0 |
我尝试了以下代码,但失败了,但这是这种格式所能达到的最大 我使用的代码:
SELECT
DateOfSour,
ISNULL(EMPName,'Total')as EmpName,
IsNULL(LblCode,'') as LblCode ,
SUM(CASE WHEN ProdType='Prod1' THEN Amount ELSE 0 END) as Prod1,
SUM(CASE WHEN ProdType='Prod2' THEN Amount ELSE 0 END) as Prod2,
SUM(CASE WHEN ProdType='Prod3' THEN Amount ELSE 0 END) as Prod3,
FROM Table1
WHERE DateOfSour between('2019-01-01') and ('2019-01-03')
GROUP BY DateOfSour, GROUPING SETS((EMPName,LblCode), ())
我使用SQL Server 2008。
编辑1:这只是两天的一个例子,我想要 给定随机日期
答案 0 :(得分:0)
您需要更多列。像这样:
SELECT COALESCE(EMPName, 'Total') as EMPName,
COALESCE(LblCode, '') as LblCode ,
'2019-01-01' as DateOfSour1,
SUM(CASE WHEN DateOfSour = '2019-01-01' AND ProdType = 'Prod1' THEN Amount ELSE 0 END) as Prod1_1,
SUM(CASE WHEN DateOfSour = '2019-01-01' AND ProdType = 'Prod2' THEN Amount ELSE 0 END) as Prod2_1,
SUM(CASE WHEN DateOfSour = '2019-01-01' AND ProdType = 'Prod3' THEN Amount ELSE 0 END) as Prod3_1,
'2019-01-02' as DateOfSour2,
SUM(CASE WHEN DateOfSour = '2019-01-02' AND ProdType = 'Prod1' THEN Amount ELSE 0 END) as Prod1_2,
SUM(CASE WHEN DateOfSour = '2019-01-02' AND ProdType = 'Prod2' THEN Amount ELSE 0 END) as Prod2_2,
SUM(CASE WHEN DateOfSour = '2019-01-02' AND ProdType = 'Prod3' THEN Amount ELSE 0 END) as Prod3_2
FROM Table1
WHERE DateOfSour IN (''2019-01-01', '2019-01-02')
GROUP BY GROUPING SETS((EMPName, LblCode), ())