一个数据库的查询有关问题
一个数据库的查询问题
字段1 字段2 字段3 序号
1 1 n1 1
1 1 n2 2
1 1 n3 3
2 2 s1 4
2 2 s2 5
2 2 s3 6
………………
如何输出
字段1 字段2 字段3 字段4 字段5
1 1 n1 n2 n3
2 2 s1 s2 s3
其中
n1 n2 n3,可是放在不同字段里,也可是在一起 n1,n2,n3
------解决方案--------------------
------解决方案--------------------
动态的交给楼下。
------解决方案--------------------
字段1 字段2 字段3 序号
1 1 n1 1
1 1 n2 2
1 1 n3 3
2 2 s1 4
2 2 s2 5
2 2 s3 6
………………
如何输出
字段1 字段2 字段3 字段4 字段5
1 1 n1 n2 n3
2 2 s1 s2 s3
其中
n1 n2 n3,可是放在不同字段里,也可是在一起 n1,n2,n3
------解决方案--------------------
;with f as
(
select id=row_number()over(partition by 字段1, 字段2 order by getdate())),* from tb
)
select
字段1, 字段2,
max(case when id=1 then 字段3 else '' end) as 字段3,
max(case when id=2 then 字段3 else '' end) as 字段4,
max(case when id=3 then 字段3 else '' end) as 字段5
from
f
group by
字段1, 字段2
------解决方案--------------------
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-06-17 10:27:19
-- Version:
-- Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86)
-- Feb 10 2012 19:13:17
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([字段1] int,[字段2] int,[字段3] varchar(2),[序号] int)
insert [tb]
select 1,1,'n1',1 union all
select 1,1,'n2',2 union all
select 1,1,'n3',3 union all
select 2,2,'s1',4 union all
select 2,2,'s2',5 union all
select 2,2,'s3',6
--------------开始查询--------------------------
;with f as
(
select id=row_number()over(partition by 字段1, 字段2 order by getdate()),* from tb
)
select
字段1, 字段2,
max(case when id=1 then 字段3 else '' end) as 字段3,
max(case when id=2 then 字段3 else '' end) as 字段4,
max(case when id=3 then 字段3 else '' end) as 字段5
from
f
group by
字段1, 字段2
----------------结果----------------------------
/* 字段1 字段2 字段3 字段4 字段5
----------- ----------- ---- ---- ----
1 1 n1 n2 n3
2 2 s1 s2 s3
(2 行受影响)
*/
动态的交给楼下。
------解决方案--------------------