0

我已经阅读了几十个关于 CASE 的答案,但不确定这是我需要在这里使用的,它似乎应该可以工作,但它不是:

Data:
OrderNum    OrderLine  PartNum
200011         1         ABC-1
200011         2         DEF-1
200012         1         XYZ-1

What I would like to return:
OrderNum   Item#
200011     MIXED
200012     XYZ-1


What I am returning instead:
OrderNum   Item#
200011     ABC-1
200011     MIXED
200012     XYZ-1

我的查询:

SELECT OrderHed.OrderNum, 
      (CASE WHEN ShipDtl.OrderLine > '1' then 'MIXED' else ShipDtl.PartNum end) as [Item#]
FROM dbo.OrderHed, dbo.ShipDtl
WHERE ShipDtl.Company = OrderHed.Company 
AND ShipDtl.OrderNum = OrderHed.OrderNum
GROUP BY OrderHed.OrderNum, ShipDtl.OrderLine, ShipDtl.Part
4

3 回答 3

1

尝试分组

SELECT OrderHed.OrderNum, 
      (CASE WHEN SUM(ShipDtl.OrderLine) > 1 then 'MIXED' else MAX(ShipDtl.PartNum) end) as [Item#]
FROM dbo.OrderHed, dbo.ShipDtl
WHERE ShipDtl.Company = OrderHed.Company 
AND ShipDtl.OrderNum = OrderHed.OrderNum
GROUP BY OrderHed.OrderNum

SQLFiddle 演示:http ://sqlfiddle.com/#!3/209d8/1

于 2013-11-07T07:24:46.787 回答
1

您没有编写您使用的数据库引擎,但如果它是 SQL 2005 及更高版本,我认为使用 COUNT 的窗口函数会使事情变得更容易,因为您不需要分组。

SELECT  DISTINCT
        OrderHed.OrderNum ,
        CASE 
            WHEN COUNT(ShipDtl.OrderLine) OVER (PARTITION BY ShipDtl.OrderNum) > 1 THEN 'MIXED'
            ELSE PartNum
        END AS [Item#]
FROM    dbo.OrderHed ,
        dbo.ShipDtl
WHERE   ShipDtl.Company = OrderHed.Company
        AND ShipDtl.OrderNum = OrderHed.OrderNum

不过,您需要 DISTINCT,因为它会每行选择一行,但每个包含多行的订单将是 MIXED,因此您可以轻松区分。

这将简单地选择 OrderNum,如果每个 ordernum Count(xxx) OVER(按 yyy 分区)存在多个订单行,它将选择“MIXED”,否则选择 partnum。然后区分结果。

于 2013-11-07T08:12:16.120 回答
0

没有强制使用CASE(有吗?)。

在您的示例CASE中,用于执行逻辑OR. 还有其他OR在 SQL 中执行逻辑的方法,例如UNION

WITH T 
     AS
     (
      SELECT OrderHed.OrderNum, ShipDtl.PartNum, ShipDtl.OrderLine
        FROM dbo.OrderHed, dbo.ShipDtl
       WHERE ShipDtl.Company = OrderHed.Company 
             AND ShipDtl.OrderNum = OrderHed.OrderNum
     )
SELECT OrderNum, PartNum
  FROM T
 WHERE OrderLine = 1
       AND OrderNum NOT IN ( 
                            SELECT OrderNum
                              FROM T T2
                             WHERE OrderLine > 1
                           )
UNION
SELECT OrderNum, 'MIXED' AS PartNum
  FROM T
 WHERE OrderLine > 1;
于 2013-11-07T08:52:16.070 回答