基础信息
CREATE TABLE [dbo].[Test](
[Year] [int] NULL,
[Name] [nvarchar](50) NULL,
[Value] [int] NULL,
[ID] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Test] ([Year], [Name], [Value], [ID]) VALUES (2001, N'柴油', 10, 1)
INSERT [dbo].[Test] ([Year], [Name], [Value], [ID]) VALUES (2001, N'煤油', 30, 2)
INSERT [dbo].[Test] ([Year], [Name], [Value], [ID]) VALUES (2002, N'汽油', 50, 3)
INSERT [dbo].[Test] ([Year], [Name], [Value], [ID]) VALUES (2002, N'柴油', 70, 4)
CREATE TABLE [dbo].[Test](
[Year] [int] NULL,
[Name] [nvarchar](50) NULL,
[Value] [int] NULL,
[ID] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Test] ([Year], [Name], [Value], [ID]) VALUES (2001, N'柴油', 10, 1)
INSERT [dbo].[Test] ([Year], [Name], [Value], [ID]) VALUES (2001, N'煤油', 30, 2)
INSERT [dbo].[Test] ([Year], [Name], [Value], [ID]) VALUES (2002, N'汽油', 50, 3)
INSERT [dbo].[Test] ([Year], [Name], [Value], [ID]) VALUES (2002, N'柴油', 70, 4)
需要实现如下效果
显示效果如下:
Name Year Value
柴油 2001 10
煤油 2001 30
汽油 2001 0
柴油 2002 70
煤油 2002 0
汽油 2002 50
Name Year Value
柴油 2001 10
煤油 2001 30
汽油 2001 0
柴油 2002 70
煤油 2002 0
汽油 2002 50
我的sql语句如下,现需要效率更高的sql语句:
SELECT year,name, sum(value) value FROM
(
SELECT year,t1.name, (CASE WHEN t1.Name=t2.Name THEN t2.value ELSE 0 END) value FROM
(SELECT * FROM Test)t2
CROSS JOIN
(SELECT DISTINCT Name FROM Test)t1
) t3
GROUP BY year,name
ORDER BY year
SELECT year,name, sum(value) value FROM
(
SELECT year,t1.name, (CASE WHEN t1.Name=t2.Name THEN t2.value ELSE 0 END) value FROM
(SELECT * FROM Test)t2
CROSS JOIN
(SELECT DISTINCT Name FROM Test)t1
) t3
GROUP BY year,name
ORDER BY year