对多个列使用数据透视-SQL Server

时间:2018-08-08 09:48:16

标签: sql sql-server pivot

我有这些表:

http://sqlfiddle.com/#!18/b871d/8

create table ItemOrder
(
ID int,
ItemNumber int,
Qty int,
Price int,
Cost int,
DateSold datetime
)

insert into ItemOrder (ID, ItemNumber, Qty, Price, Cost, DateSold)
Values
('1', '145', '5', '50', '25', '08-06-18'),
('2', '145', '5', '50', '25', '07-04-18'),
('3', '145', '5', '50', '25', '06-06-18')

结果:

| ID | ItemNumber |             DateSold | Qty | Price | Cost |
|----|------------|----------------------|-----|-------|------|
|  1 |        145 | 2018-08-06T00:00:00Z |   5 |    50 |   25 |
|  2 |        145 | 2018-07-04T00:00:00Z |   5 |    50 |   25 |
|  3 |        145 | 2018-06-06T00:00:00Z |   5 |    50 |   25 |

但是我一直在寻找按月划分的结果,例如:

例如

| ID | ItemNumber | Aug-18 Qty | Aug-18 Price | Aug-18 Cost |July-18 Qty|July-18 Price| 
|----|------------|------------|--------------|-------------|
|  1 |        145 |   5        |           50 |          25 |

以此类推。...

select 
ID,
ItemNumber,
DateSold,
(
select ID, ItemNumber, Qty, DateSold
from ItemOrder
) x
PIVOT 
(
SUM(QTY), SUM(Price), SUM(Cost) FOR DateSold in(DateSold1)
) p;

我尝试了几次查询,但似乎无法正确执行。任何指导都会很棒。谢谢

2 个答案:

答案 0 :(得分:1)

我建议只进行条件聚合:

<speak>
    the contact number is <say-as interpret-as="telephone"> 9876-543-210 </say-as>
</speak> 

Here是一个SQL提琴。

答案 1 :(得分:0)

WITH Table1 AS
(
select 
ID,
ItemNumber,
CAST(year(DateSold) AS VARCHAR(4)) + ' ' + DATENAME(m, DateSold) AS [DateSold2],
Qty
from ItemOrder
)

select * from Table1
pivot (sum(Qty) for[DateSold2] IN ([2018 August], [2018 July], [2018 June])) as d

更多我想要的东西:)

http://sqlfiddle.com/#!18/b871d/23