行变列(交叉表)查询语句的写法求助.
建立测试环境语句:
CREATE TABLE [TABLE1] (
[iCode] [int] NOT NULL,
[iDate] [char] (50) NULL,
[State] [char] (50) NULL)
ALTER TABLE [TABLE1] WITH NOCHECK ADD CONSTRAINT [PK_TABLE1] PRIMARY KEY NONCLUSTERED ( [iCode] )INSERT [TABLE1] ([iCode],[iDate],[State]) VALUES ( 1, '2007-8-9 ', '30 ')
INSERT [TABLE1] ([iCode],[iDate],[State]) VALUES ( 2, '2007-8-8 ', '60 ')
INSERT [TABLE1] ([iCode],[iDate],[State]) VALUES ( 3, '2007-2-3 ', '30 ')
CREATE TABLE [TABLE2] (
[AutoNo] [int] IDENTITY (1, 1) NOT NULL,
[iCode] [int] NULL,
[ItemName] [char] (100) NULL,
[ItemValue] [char] (100) NULL)
ALTER TABLE [TABLE2] WITH NOCHECK ADD CONSTRAINT [PK_TABLE2] PRIMARY KEY NONCLUSTERED ( [AutoNo] )SET IDENTITY_INSERT [TABLE2] ON
INSERT [TABLE2] ([AutoNo],[iCode],[ItemName],[ItemValue]) VALUES ( 1,1, '用胶点 ', '发动机 ')
INSERT [TABLE2] ([AutoNo],[iCode],[ItemName],[ItemValue]) VALUES ( 2,1, '被粘材料 ', '内缸 ')
INSERT [TABLE2] ([AutoNo],[iCode],[ItemName],[ItemValue]) VALUES ( 3,1, '工作介质 ', '机油 ')
INSERT [TABLE2] ([AutoNo],[iCode],[ItemName],[ItemValue]) VALUES ( 4,1, '工作温度 ', '200 ')
INSERT [TABLE2] ([AutoNo],[iCode],[ItemName],[ItemValue]) VALUES ( 5,2, '用胶点 ', '螺纹封 ')
INSERT [TABLE2] ([AutoNo],[iCode],[ItemName],[ItemValue]) VALUES ( 6,2, '工作温度 ', '300 ')
SET IDENTITY_INSERT [TABLE2] OFF
表一和表二是主从表的关系
现在想得到的查询结果:
iCode | iDate | State |用胶点| 被粘材料 |工作介质 |工作温度
-------------------------
1 2007-8-9 30 发动机 内缸 机油 200
2 2007-8-8 60 螺纹封 null null 300
------解决方案--------------------select a.*
,max(case when b.ItemName = '用胶点 ' then ItemValue end) as 用胶点
,max(case when b.ItemName = '被粘材料 ' then ItemValue end) as 被粘材料
,max(case when b.ItemName = '工作介质 ' then ItemValue end) as 工作介质
,max(case when b.ItemName = '工作温度 ' then ItemValue end) as 工作温度
from TABLE1 a
join table2 b on b.iCode = a.iCode
group by a.icode,a.idate,a.state