我的表格设计如下:
BSales:
PCode SaleDate SaleValue
1 2015-01-01 50000
2 2015-01-01 50000
3 2015-01-01 50000
4 2015-01-01 50000
5 2015-01-01 50000
1 2015-01-02 50000
2 2015-01-02 50000
3 2015-01-02 50000
4 2015-01-02 50000
5 2015-01-02 50000
select PCode,SaleDate,SUM(SaleValue) as Sales
from [BSales]
where SaleDate between '2015-01-01' and '2015-01-05'
group by PCode,SaleDate
这部分满足了我的愿望输出。但我想输出如下:
PCode '2015-01-01' '2015-01-02' '2015-01-03' '2015-01-04' '2015-01-05'
1 5000 50000 0 0 0
2 5000 50000 0 0 0
3 5000 50000 0 0 0
4 5000 50000 0 0 0
5 5000 50000 0 0 0
是否可以使用sql查询?或T-SQL?或使用存储过程?非常感谢任何帮助。
答案 0 :(得分:2)
这是支点任务:
DECLARE @t TABLE
(
PCode INT ,
SaleDate DATE ,
SaleValue MONEY
)
INSERT INTO @t
VALUES ( 1, '2015-01-01', 50000 ),
( 2, '2015-01-01', 50000 ),
( 3, '2015-01-01', 50000 ),
( 4, '2015-01-01', 50000 ),
( 5, '2015-01-01', 50000 ),
( 1, '2015-01-02', 50000 ),
( 2, '2015-01-02', 50000 ),
( 3, '2015-01-02', 50000 ),
( 4, '2015-01-02', 50000 ),
( 5, '2015-01-02', 50000 )
SELECT PCode ,
ISNULL([2015-01-01], 0) AS [2015-01-01] ,
ISNULL([2015-01-02], 0) AS [2015-01-02] ,
ISNULL([2015-01-03], 0) AS [2015-01-03] ,
ISNULL([2015-01-04], 0) AS [2015-01-04] ,
ISNULL([2015-01-05], 0) AS [2015-01-05]
FROM @t PIVOT( MAX(SaleValue) FOR SaleDate IN ( [2015-01-01], [2015-01-02],
[2015-01-03], [2015-01-04],
[2015-01-05] ) ) p
输出:
PCode 2015-01-01 2015-01-02 2015-01-03 2015-01-04 2015-01-05
1 50000.00 50000.00 0 0 0
2 50000.00 50000.00 0 0 0
3 50000.00 50000.00 0 0 0
4 50000.00 50000.00 0 0 0
5 50000.00 50000.00 0 0 0
答案 1 :(得分:1)
您需要查看T-SQL中的数据透视表选项。
例如(未经测试!)
SELECT *
FROM BSales
PIVOT(SUM(SaleValue)
FOR SaleDate IN ([2015-01-01], [2015-01-02]
, [2015-01-03], [2015-01-04], [2015-01-05])) AS PVTTable
这是一个完整的教程。
http://sqlhints.com/2014/03/10/pivot-and-unpivot-in-sql-server/