我有这些桌子:
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;
我试过几个问题,但似乎都做不好。这对任何指导都是很好的。谢谢