【问题标题】:SQL Server combine multiple rows into oneSQL Server 将多行合二为一
【发布时间】:2016-12-29 18:27:26
【问题描述】:

我想将多行合并为一行

Inv_ID = 188、198 和 82 的客户端应合并为一行

结果应该有两行..

ClientID | Input(188) | Input(198 | Input(82)             |Date(188)         |Date (198)
--------------------------------------------------------------------
133      | Yes        | yes       | Referred to comm Pres | 2016-08-16 01:00 | 2016-8-01
133      | yes        | yes       | Referred to comm Pres | 2016-08-17 00:00 | 2016-08-17

谁能帮帮我?

谢谢。

【问题讨论】:

  • 您想显示这些行的哪些部分?例如。 M_ID 的哪个值,Input 的哪个值??
  • 我希望结果如下 ClientID |输入(188) |输入(198 | 输入(82) |日期(188) |日期(198) 133 |是|是|参考comm Pres | 2016-08-16 01:00| 2016-8-01:133|是|是|参考通讯新闻 |2016-08-17 00:00 |2016-08-17
  • 我已经在描述中显示了我期望的结果
  • 预期结果不清楚。请说清楚。
  • @NEER 我想将 Inv_id = 188,198,82 的客户组合在一起,查询结果应该给我客户 ID,分别输入 188,198 和 82,日期分别为 188,198

标签: sql-server sql-server-2008 sql-server-2014


【解决方案1】:

我认为关键在于了解 188,198 和 88 属于哪个区块。在下面的 cte 中,我的工作基于 88 始终终止一个块,并将 88 的 rowid 分配给小于它的所有 rowid - 从而启用 group by。

declare @t table(client_id int, m_id int,chid int,inv_id int,input varchar(20),dt datetime,rowid int)
insert into @t values
(133,928,9581,188,'yes_b1','2016-08-16 01:00:00:000',1),
(133,929,9581,198,'yes_b1','2016-08-16 01:10:00:000',2),
(133,930,9581,82,'referred_b1','2016-08-16 01:30:00:000',3),
(133,935,9584,188,'yes_b2','2016-08-16 01:00:00:000',5),
(133,936,9584,198,'yes_b2','2016-08-16 01:00:00:000',6),
(133,937,9584,82,'referred_b2','2016-08-16 01:00:00:000',7)

;with cte as
(
select s.*,
        lag(s.hi,1,0) over (order by s.inv_id) as lo 
from
(
select  inv_id,rowid as hi
from @t
where inv_id = 82
)s
)
select t.client_id,
        max(case when t.inv_id = 188 then input end) 'input(188)',
        max(case when t.inv_id = 198 then input end) 'input(198)',
        max(case when t.inv_id = 82  then input end) 'input(82)',
        max(case when t.inv_id = 188 then dt end) 'date(188)',
        max(case when t.inv_id = 198 then dt end) 'date(198)',
        max(case when t.inv_id = 82  then dt end) 'date(82)' 
from @t t
join cte on rowid <= cte.hi and rowid > cte.lo
group by client_id,cte.hi

结果

client_id   input(188)           input(198)           input(82)            date(188)               date(198)               date(82)
----------- -------------------- -------------------- -------------------- ----------------------- ----------------------- -----------------------
        133 yes_b1               yes_b1               referred_b1          2016-08-16 01:00:00.000 2016-08-16 01:10:00.000 2016-08-16 01:30:00.000
        133 yes_b2               yes_b2               referred_b2          2016-08-16 01:00:00.000 2016-08-16 01:00:00.000 2016-08-16 01:00:00.000

【讨论】:

  • 非常感谢 P.Salmon
猜你喜欢
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多