SQL Group By Clause和Empty Entries

时间:2013-10-22 13:29:02

标签: sql sql-server-2005

我有一个SQL Server 2005查询,我现在正在尝试组装,但是我遇到了一些困难。

我有一个基于5列的group by子句:Project,Area,Name,User,Engineer。

工程师来自另一张桌子,是一对多的关系

WITH TempCTE
AS (
    SELECT htce.HardwareProjectID AS ProjectId
        ,area.AreaId AS Area
        ,hs.NAME AS 'Status'
        ,COUNT(*) AS Amount
        ,MAX(htce.DateEdited) AS DateModified
        ,UserEditing AS LastModifiedName
        ,Engineer
        ,ROW_NUMBER() OVER (
            PARTITION BY htce.HardwareProjectID
            ,area.AreaId
            ,hs.NAME
            ,htce.UserEditing ORDER BY htce.HardwareProjectID
                ,Engineer DESC
            ) AS row
    FROM HardwareTestCase_Execution AS htce
    INNER JOIN HardwareTestCase AS htc ON htce.HardwareTestCaseID = htc.HardwareTestCaseID
    INNER JOIN HardwareTestGroup AS htg ON htc.HardwareTestGroupID = htg.HardwareTestGroupId
    INNER JOIN Block AS b ON b.BlockId = htg.BlockId
    INNER JOIN Area ON b.AreaId = Area.AreaId
    INNER JOIN HardwareStatus AS hs ON htce.HardwareStatusID = hs.HardwareStatusId
    INNER JOIN j_Project_Testcase AS jptc ON htce.HardwareProjectID = jptc.HardwareProjectId AND htce.HardwareTestCaseID = jptc.TestcaseId
    WHERE (htce.DateEdited > @LastDateModified)
    GROUP BY htce.HardwareProjectID
        ,area.AreaId
        ,hs.NAME
        ,htce.UserEditing
        ,jptc.Engineer
    )

enter image description here

我想要的是要能够处理空的工程师专栏。我不希望此列有一个空白的第二个条目(其中row = 2)。

我想做什么:

  1. 将“行”值为1&的项目分组。 2在一起。
  2. 选择非空的工程师。
  3. 如果没有匹配的行= 2,请勿取消选择工程师。
  4. 我尝试了一系列连接尝试让事情发挥作用。到目前为止没有运气。

1 个答案:

答案 0 :(得分:0)

使用j_Project_Testcase PIVOT( MAX(Engineer) for Row in ( [1], [2] ),然后选择ISNULL( [1],[2])以选择Engineer

如果你设置一个SQL小提琴,我可以给你一个更健壮的例子

请尝试阅读:PIVOT and UNPIVOT