如何获取记录中的所有行?

时间:2017-10-16 11:50:41

标签: sql sql-server

如何让一行中发生的所有事件都发生?

示例:(它没有任何意义,只是为了一个例子)

Id Name   Event    Date
1  John   Running  2017/09/13
2  Mary   Sleeping 2017/08/21
3  Karl   Sleeping 2017/07/30
1  John   Tired    2017/10/16
2  Mary   Playing  2017/10/16

我想得到如下结果:

Id Name   Event              Date
1  John   Running, Tired     2017/10/16
2  Mary   Sleeping, Playing  2017/10/16
3  Karl   Sleeping           2017/07/30

事件记录按事件日期升序显示。

最后,它应该返回所有那些事件行的最大日期

5 个答案:

答案 0 :(得分:1)

SELECT DISTINCT B.id, Name, MAX(Date) Date,
    substring(
        (
            SELECT ','+A.Event  AS [text()]
            FROM yourtable A
            WHERE A.Id = B.Id
            ORDER BY A.Id
            For XML PATH ('')
        ), 2, 1000) Event
FROM yourtable B
GROUP BY B.Id, Name

输出

id  Name    Date                    Event
1   John    2017-10-16T00:00:00Z    Running,Tired
3   Karl    2017-07-30T00:00:00Z    Sleeping
2   Mary    2017-10-16T00:00:00Z    Sleeping,Playing

SQL小提琴:http://sqlfiddle.com/#!6/2fd81/13/0

答案 1 :(得分:0)

试试这个:

http://localhost:4200/#state=c93e5c1f-0cb1-404f-81b6-202eef7add4d&code=VziF6tlMnl_iZaNWoJBWtiz0j6TIKAcb5_KCu29Nygo.5fb5511b-624c-4423-8232-bdcce3137bf4

here抓取列表聚合。

不确定你是如何聚合Id所以我省略了。

答案 2 :(得分:0)

您的表格数据

DataGridView

<强>查询

select * into #tab from (
select 1  id,'John'as Name ,  'Running'  [Event],'2017/09/13' [Date]
union all
select 2 , 'Mary'   ,'Sleeping', '2017/08/21'
union all
select 3,  'Karl'  , 'Sleeping', '2017/07/30'
union all
select 1,  'John',   'Tired' ,   '2017/10/16'
union all
select 2 , 'Mary' ,  'Playing' , '2017/10/16'
)as a 

所需输出

select distinct id,Name,stuff (
(select ','+[Event] from #tab where [id]=t.id for xml path('')),1,1,'')as Event,max([date]) Date_
from #tab t
group by id,Name
order by id

答案 3 :(得分:0)

您应该使用XML方法和STUFF函数来生成Single Row数据:

SELECT T.ID,
       T.Name,
       STUFF(
            (
                SELECT ','+[EVENT]
                FROM <table_name>
                WHERE ID = T.ID FOR XML PATH('')
            ), 1, 1, '') [Event],
       REPLACE(MAX([Date]), '-', '/') [Date]
FROM <table_name> T
GROUP BY T.ID,
         T.NAME
ORDER BY ID;

结果:

   ID          Name      Event              Date
----------- --------- ------------------ ------------
   1           John      Running,Tired      2017/10/16
   2           Mary      Sleeping,Playing   2017/10/16
   3           Karl      Sleeping           2017/07/30

答案 4 :(得分:0)

最简单快捷的方法是在普通SELECT中聚合STUFF命令中的所有事件。 这可能是最快的执行时间:

SELECT
  aggregateevents.Name,
  Event = STUFF
  (
    (
      SELECT ', ' + Event
      FROM myawesomeeventstable eventlist
      WHERE eventlist.Name = aggregateevents.Name
      FOR XML PATH('')
    ),
    1,
    2,
    ''
  ),
  MAX(Date) 
FROM
  myawesomeeventstable aggregateevents 
GROUP BY
  aggregateevents.Name