SQl Server多行分组

时间:2016-09-26 08:32:29

标签: sql sql-server group-by

假设我有这两张桌子:

ID  Time  UserId
1   08:00   55
2   08:00   22
3   08:00   04
4   09:00   17
5   11:00   11
...etc...

UserId  Name
01      Brian
02      Francis
03      David
...etc...

我想要的结果是:

Hours(distinct)   Name
08:00             Franck,Michelle,Damian
09:00             Indiana, Robert

实际上,我希望在第一列中列出所有不同的小时数,并将所有用户的名称列为一行。我试过这个问题:

  

SELECT distinct convert(varchar(25),Time,120),test = STUFF((   SELECT','+名称来自T2 WHERE T1.UserId = T2.Id FOR XML PATH('')),   1,1,'')从T1组BY时间

查询在没有组的情况下工作,但是它会触发错误“列'UserId'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

试试这个

SELECT DISTINCT
    T.Time
    STUFF(
        (SELECT
            ',' + T2.Name
        FROM
            Table1 T1 INNER JOIN 
            Table2 T2 ON T1.UserId = T2.UserId
        WHERE
            T1.Time = T.Time
        FOR XML PATH('')
    ), 1, 1, '') A
FROM
    Table1 T

答案 1 :(得分:1)

XML聚合必须仅依赖于GROUP BY中列出的列,在您的情况下为time

SELECT distinct convert (varchar(25),Time ,120) 
 ,test = STUFF (( 
    SELECT ',' + Name 
    FROM T2 
    WHERE T2.UserId IN (
         SELECT T3.UserID 
         FROM T1 AS T3
         WHERE T3.time=T0.time)
   FOR XML PATH('')), 1,1,'') 
FROM T1 as T0 
GROUP BY Time

答案 2 :(得分:0)

您可以尝试这样的查询

;WITH cte
AS (SELECT
  t1.time, t1.userid, t2.name
FROM tab1 t1
JOIN tab2 t2
  ON t1.userid = t2.userid)
SELECT
  c.time,
  (STUFF((SELECT ',' + d.name
  FROM cte d
  WHERE c.time = d.time
  FOR xml PATH ('')), 1, 1, '')) AS Test
FROM cte c
GROUP BY c.time