结合SQL Query的结果

时间:2015-07-09 18:34:37

标签: sql sql-server-2008-r2

我已经做了一些研究看似的简单任务,但却未能找到一个简单的解决方案。我想用最简单的术语提出这个问题,以便其他人和我自己可以从类似的情况中受益。我遇到了一个需要重构的查询,产生了一些奇怪的结果。

转换这些结果的最佳方法是什么:

ID    Customer    CustomerID (US)    CustomerID (CA)   CustomerID (EU)
-----------------------------------------------------------------------
1     XYZ         XYZ - US           NULL              NULL
2     XYZ         NULL               XYZ - CA          NULL
3     XYZ         NULL               NULL              XYZ - EU

进入这个:

ID    Customer    CustomerID (US)    CustomerID (CA)   CustomerID (EU)
-----------------------------------------------------------------------
1     XYZ         XYZ - US           XYZ - CA          XYZ - EU

如果有多种方法,那么遵循最新最佳做法的最佳方式是什么?

以下是一些当前产生第一批结果的示例代码:

    SELECT Header.ID,
        Header.Customer,
        CASE Detail.Location
            WHEN 'US' THEN Detail.CustomerID
            ELSE NULL
        END AS [CustomerID (US)],
        CASE Detail.Location
            WHEN 'CA' THEN Detail.CustomerID
            ELSE NULL
        END AS [CustomerID (CA)],
        CASE Detail.Location
            WHEN 'EU' THEN Detail.CustomerID
            ELSE NULL
        END AS [CustomerID (EU)]
    FROM dbo.Header AS Header 
        LEFT OUTER JOIN dbo.Detail AS Detail
            ON Header.ID = Detail.HeaderID

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:2)

你只想要聚合:

SELECT MIN(Header.ID) as ID, Header.Customer,
       MAX(CASE Detail.Location WHEN 'US' THEN Detail.CustomerID
           END) AS [CustomerID (US)],
       MAX(CASE Detail.Location WHEN 'CA' THEN Detail.CustomerID
           END) AS [CustomerID (CA)],
       MAX(CASE Detail.Location WHEN 'EU' THEN Detail.CustomerID
           END) AS [CustomerID (EU)]
FROM dbo.Header LEFT OUTER JOIN
     dbo.Detail Detail
     ON Header.ID = Detail.HeaderID
GROUP BYHeader.Customer