有没有办法在sql server中的情况下选择多个值

时间:2017-01-10 11:59:10

标签: sql-server case

我有以下查询

    SELECT
        ip.ITEMID AS ItemID,
        ip.CoUkScreenName AS Name,
        CASE 
            WHEN
                (SELECT COUNT(*) FROM 
                    (SELECT c.CarbonFP, c.Unit, c.Methodology FROM [dbo].[vw_carbon_ChildProducts] AS c
                        WHERE c.ParentItemID = ip.ITEMID
                        GROUP BY c.CarbonFP, c.Unit, c.Methodology
                    ) AS CountResult
                ) = 1
            THEN 
                (SELECT TOP 1 c.CarbonFP FROM [dbo].[vw_carbon_ChildProducts] AS c WHERE c.ParentItemID = ip.ITEMID)
            ELSE
                NULL
        END AS CarbonFP,
        CASE 
            WHEN
                (SELECT COUNT(*) FROM 
                    (SELECT c.CarbonFP, c.Unit, c.Methodology FROM [dbo].[vw_carbon_ChildProducts] AS c
                        WHERE c.ParentItemID = ip.ITEMID
                        GROUP BY c.CarbonFP, c.Unit, c.Methodology
                    ) AS CountResult
                ) = 1
            THEN 
                (SELECT TOP 1 c.Unit FROM [dbo].[vw_carbon_ChildProducts] AS c WHERE c.ParentItemID = ip.ITEMID)
            ELSE
                NULL
        END AS Unit,
        CASE 
            WHEN
                (SELECT COUNT(*) FROM 
                    (SELECT c.CarbonFP, c.Unit, c.Methodology FROM [dbo].[vw_carbon_ChildProducts] AS c
                        WHERE c.ParentItemID = ip.ITEMID
                        GROUP BY c.CarbonFP, c.Unit, c.Methodology
                    ) AS CountResult
                ) = 1
            THEN 
                (SELECT TOP 1 c.Methodology FROM [dbo].[vw_carbon_ChildProducts] AS c WHERE c.ParentItemID = ip.ITEMID)
            ELSE
                NULL
        END AS Methodology
    FROM
        MARCMSITEMPRESENTATION ip
        INNER JOIN (SELECT DISTINCT (cp.ParentItemID) FROM [dbo].[vw_carbon_ChildProducts] AS cp) AS p ON p.ParentItemID = ip.ITEMID

这很好但我想知道是否有可能在同一个案例中选择所有3个值而不是一次只能做一个,或者如果有更好的方法来构造这个查询,因为它看起来效率低下(我目前没有查询问题 - 只考虑可扩展性)必须做三次相同的查询才能获得这三个值

1 个答案:

答案 0 :(得分:2)

使用OUTER APPLY

SELECT . . .,
       c.*
FROM MARCMSITEMPRESENTATION ip INNER JOIN
     (SELECT DISTINCT cp.ParentItemID
      FROM [dbo].[vw_carbon_ChildProducts] AS cp
     ) p
     ON p.ParentItemID = ip.ITEMID OUTER APPLY
     (SELECT c.*
      FROM [dbo].[vw_carbon_ChildProducts] c
      WHERE c.ParentItemID = ip.ITEMID
     ) c

一般情况下,如果没有TOP,则不应使用ORDER BY。在原始版本中,三列可能来自不同的行。在这个版本中,所有三列都来自同一行,但哪一行是不确定的。

编辑:

仅在计数为1时匹配:

SELECT . . .,
       c.*
FROM MARCMSITEMPRESENTATION ip INNER JOIN
     (SELECT DISTINCT cp.ParentItemID
      FROM [dbo].[vw_carbon_ChildProducts] AS cp
     ) p
     ON p.ParentItemID = ip.ITEMID OUTER APPLY
     (SELECT c.CarbonFP, c.Unit, c.Methodology
      FROM [dbo].[vw_carbon_ChildProducts] c
      WHERE c.ParentItemID = ip.ITEMID 
      GROUP BY c.CarbonFP, c.Unit, c.Methodology
      HAVING COUNT(*) = 1
     ) c