SQL使用联合和分组依据将行合并为一行

时间:2018-07-10 05:59:58

标签: sql sql-server union

enter image description here

enter image description here

我想向我的查询寻求帮助。我想得到一个如我的图像所示的结果。我喜欢将GROUP BYUNION一起使用,但无法获得想要的结果。

这是我的示例查询:

SELECT * 
FROM
    (SELECT 
         '' as AccomplishmentDate, ETRDate, ProjectName, EquipmentName, 
         0 as AccomplishmentActualHour, ETRActualHour 
     FROM 
         Table1

     UNION

     SELECT 
         AccomplishmentDate, '' AS ETRDate, ProjectName, EquipmentName,
         AccomplishmentActualHour, 0 AS ETRActualHour 
     FROM 
         Table1) AS Transaction

提前感谢:)

1 个答案:

答案 0 :(得分:1)

如果我理解正确,则可以使用MAX函数和GROUP BY来实现

SELECT 
       MAX(AccomplishmentDate),
       MAX(ETRDate),
       ProjectName,
       EquipmentName,
       MAX(AccomplishmentActualHour),
       MAX(ETRActualHour) 
FROM
(
   SELECT NULL as AccomplishmentDate, ETRDate, ProjectName,EquipmentName, 0 as 
        AccomplishmentActualHour, ETRActualHour 
   FROM T
   UNION
   SELECT AccomplishmentDate, NULL as ETRDate, ProjectName,EquipmentName,
        AccomplishmentActualHour,0 as ETRActualHour 
   FROM T
) t
GROUP BY  
     ProjectName,EquipmentName

sqlfiddle:http://sqlfiddle.com/#!18/337ff/2

从您的图像数据看来,这可能是可行的。

SELECT MAX(AccomplishmentDate),
       MAX(ETRDate),
       ProjectName,
       EquipmentName,
       MAX(AccomplishmentActualHour),
       MAX(ETRActualHour)
FROM Table1
GROUP BY  ProjectName,EquipmentName

编辑

您需要编写子查询以创建ROW_NUMBER,然后添加GROUP BYMAX

;WITH CTE AS(
   SELECT NULL as AccomplishmentDate, ETRDate, ProjectName,EquipmentName, 0 as 
          AccomplishmentActualHour, ETRActualHour,1 grp
   FROM T
   UNION
   SELECT AccomplishmentDate, NULL as ETRDate, ProjectName,EquipmentName,
          AccomplishmentActualHour,0 as ETRActualHour,2
   FROM T
),grpCTE AS(
SELECT *,ROW_NUMBER() OVER(PARTITION BY grp ORDER BY grp) rn
FROM CTE
)
SELECT MAX(AccomplishmentDate),
       MAX(ETRDate),
       ProjectName,
       EquipmentName,
       MAX(AccomplishmentActualHour),
       MAX(ETRActualHour) 
FROM grpCTE
group by 
        ProjectName,
       EquipmentName,
       rn

sqlfiddle:http://sqlfiddle.com/#!18/43f3c/25

如果您有新问题,可以创建一个新主题:)