我有以下两个表(带有数据的SQL脚本):
CREATE TABLE [dbo].[Item_Master](
[Item_Name] [varcha`enter code here`r](20) NOT NULL,
[Item_Cost] [int] NULL,
CONSTRAINT [PK_Item_Master] PRIMARY KEY CLUSTERED
(
[Item_Name] ASC
)
)
GO
CREATE TABLE [dbo].[ItemAnalysis]
(
Item_Name nvarchar(20) NOT NULL,
Analysis_Type nvarchar(20) NOT NULL,
Item_Quantity int NOT NULL,
Analysis_Date date NOT NULL
)
GO
insert Item_Master (Item_Name, Item_Cost)
values ('item1', 2)
insert Item_Master (Item_Name, Item_Cost)
values ('item2', 3)
insert ItemAnalysis (Item_Name, Analysis_Type, Item_Quantity, Analysis_Date)
values ('item1', 'A', 10, '2012-01-14')
insert ItemAnalysis (Item_Name, Analysis_Type, Item_Quantity, Analysis_Date)
values ('item1', 'B', 12, '2012-01-14')
insert ItemAnalysis (Item_Name, Analysis_Type, Item_Quantity, Analysis_Date)
values ('item2', 'A', 11, '2012-01-14')
insert ItemAnalysis (Item_Name, Analysis_Type, Item_Quantity, Analysis_Date)
values ('item2', 'B', 14, '2012-01-14')
insert ItemAnalysis (Item_Name, Analysis_Type, Item_Quantity, Analysis_Date)
values ('item1', 'A', 9, '2012-02-11')
insert ItemAnalysis (Item_Name, Analysis_Type, Item_Quantity, Analysis_Date)
values ('item1', 'B', 11, '2012-02-11')
insert ItemAnalysis (Item_Name, Analysis_Type, Item_Quantity, Analysis_Date)
values ('item2', 'A', 20, '2012-02-11')
insert ItemAnalysis (Item_Name, Analysis_Type, Item_Quantity, Analysis_Date)
values ('item2', 'B', 7, '2012-02-11')
我需要这样的输出:
Item_Name| Item_Cost| Analysis_Date| Type_A_Quantity| Type_B_Quantity
----------------------------------------------------------------------
item1|2|2012-01-14|10|12
item2|3|2012-01-14|11|14
item1|2|2012-02-11|9|11
item2|3|2012-02-11|20|7
分析何时完成没有规律性(例如每周或每月等),但每当分析完成时,就会在一天内对所有项目进行分析。
答案 0 :(得分:1)
SELECT
m.Item_Name,
m.Item_Cost,
a.Analysis_Date,
SUM(CASE WHEN Analysis_Type = 'A' THEN Item_Quantity ELSE 0 END) as Type_A_Quantity,
SUM(CASE WHEN Analysis_Type = 'B' THEN Item_Quantity ELSE 0 END) as Type_B_Quantity
FROM Item_Master m
JOIN ItemAnalysis a
ON m.Item_Name = a.Item_Name
GROUP BY m.Item_Name, m.Item_Cost, a.Analysis_Date