1、原表:
id proid proname
1 1 M
1 2 F
2 1 N
2 2 G
3 1 B
3 2 A
查询后的表:
id pro1 pro2
1 M F
2 N G
3 B A
写出查询语句
构建环境USE [aa] GO /****** Object: Table [dbo].[t] Script Date: 03/09/2011 10:50:46 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[t]( [id] [int] NULL, [proid] [int] NULL, [proname] [nvarchar](50) NULL ) ON [PRIMARY] GO INSERT [dbo].[t] ([id], [proid], [proname]) VALUES (1, 1, N'M') INSERT [dbo].[t] ([id], [proid], [proname]) VALUES (1, 2, N'F') INSERT [dbo].[t] ([id], [proid], [proname]) VALUES (2, 1, N'N') INSERT [dbo].[t] ([id], [proid], [proname]) VALUES (2, 2, N'G') INSERT [dbo].[t] ([id], [proid], [proname]) VALUES (3, 1, N'B') INSERT [dbo].[t] ([id], [proid], [proname]) VALUES (3, 2, N'A')
答案select id, pro1=(select proname from t where Id = x.Id and proid=1), pro2=(select proname from t where id = x.Id and proId=2) from t x group by id
2、
面试题:怎么把这样一个表儿
year month amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
查成这样一个结果
year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4
环境 /****** Object: Table [dbo].[t] Script Date: 03/09/2011 11:09:06 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[t]( [year] [int] NULL, [month] [int] NULL, [amount] [float] NULL ) ON [PRIMARY] GO INSERT [dbo].[t] ([year], [month], [amount]) VALUES (1991, 1, 1.1) INSERT [dbo].[t] ([year], [month], [amount]) VALUES (1991, 2, 1.2) INSERT [dbo].[t] ([year], [month], [amount]) VALUES (1991, 3, 1.3) INSERT [dbo].[t] ([year], [month], [amount]) VALUES (1991, 4, 1.4) INSERT [dbo].[t] ([year], [month], [amount]) VALUES (1992, 1, 2.1) INSERT [dbo].[t] ([year], [month], [amount]) VALUES (1992, 2, 2.2) INSERT [dbo].[t] ([year], [month], [amount]) VALUES (1992, 3, 2.3) INSERT [dbo].[t] ([year], [month], [amount]) VALUES (1992, 4, 2.4)
答案select [year], m1=(select amount from t where [year]=x.[year] and [month]=1), m2=(select amount from t where [year]=x.[year] and [month]=2), m3=(select amount from t where [year]=x.[year] and [month]=3), m4=(select amount from t where [year]=x.[year] and [month]=4) from t x group by [year]