如何将每次评估的CASE语句限制为1行

时间:2018-05-17 16:47:28

标签: sql-server tsql

所以我有一个包含2行的简单查询:

SELECT DISTINCT
    o.OrderNo,
    CASE
        WHEN od.PartNo LIKE '%Amend%' AND od.User_Currency2 IS NOT NULL THEN od.User_Currency2
        WHEN od.PartNo LIKE '%Amend%' AND od.User_Currency1 IS NOT NULL THEN od.User_Currency1
        ELSE o.OrderTotal
        END AS [OrderTotal] 
FROM OrderDet od
   JOIN Orders o ON od.OrderNo = o.OrderNo
WHERE o.OrderNo LIKE '%E'
ORDER BY o.OrderNo

在我的CASE语句中,对于每个订单,如果满足第一个条件,我希望它只返回那个并忽略其他2个选项,条件#2相同,如果前两个条件失败,则默认为ELSE

问题是我每个订单都有多行,如下所示:

enter image description here

如何限制每个订单只有1条记录?我认为CASE语句按顺序进行评估并且只会吐出1个值,但在我的情况下,每个订单都会从每个订单的CASE语句中返回多个结果

1 个答案:

答案 0 :(得分:2)

使用一系列查询联合并按User_Currency2 / User_Currency1值过滤,如下所示:

SELECT DISTINCT
    o.OrderNo,
    od.User_Currency2 AS [OrderTotal]
FROM OrderDet od
   JOIN Orders o ON od.OrderNo = o.OrderNo
WHERE
  o.OrderNo LIKE '%E' AND
  od.PartNo LIKE '%Amend%' AND
  od.User_Currency2 IS NOT NULL
UNION
SELECT DISTINCT
    o.OrderNo,
    od.User_Currency2 AS [OrderTotal]
FROM OrderDet od
   JOIN Orders o ON od.OrderNo = o.OrderNo
WHERE
  o.OrderNo LIKE '%E' AND
  od.PartNo LIKE '%Amend%' AND
  od.User_Currency2 IS NULL AND
  od.User_Currency1 IS NOT NULL
UNION
SELECT DISTINCT
    o.OrderNo,
    od.OrderTotal
FROM OrderDet od
   JOIN Orders o ON od.OrderNo = o.OrderNo
WHERE
  o.OrderNo LIKE '%E' AND
  od.PartNo LIKE '%Amend%' AND
  od.User_Currency2 IS NULL AND
  od.User_Currency1 IS NULL
ORDER BY
  o.OrderNo