SQL Query与多个CASE语句使用与THEN相同的字段

时间:2016-02-29 18:56:18

标签: sql-server case

知道为什么我的UOMC.ToUnitOfMeasure的case语句返回NULL?如果我反转并在from字段之前显示To字段,那么将起作用但是不会。

->

2 个答案:

答案 0 :(得分:1)

您有两个引用(TO和FROM),因此您必须引用您的目录UNITOFMEASURE两次:

SELECT
  ...
  UOM_FROM.SYMBOL as 'FROM UNIT',
  UOM_TO.SYMBOL as 'TO UNIT'
FROM
...
INNER JOIN UNITOFMEASURECONVERSION AS UOMC ON UOMC.PRODUCT =  ECORESPRODUCT.RECID
INNER JOIN UNITOFMEASURE AS UOM_FROM ON UOM_FROM.RECID = UOMC.FROMUNITOFMEASURE
INNER JOIN UNITOFMEASURE AS UOM_TO ON UOM_TO.RECID = UOMC.TOUNITOFMEASURE

答案 1 :(得分:0)

这最终成为正确的语法。缺少匹配TO单元和FROM所需的额外连接。     SELECT ECORESPRODUCT.DISPLAYPRODUCTNUMBER, ECORESPRODUCT.SEARCHNAME, INVENTTABLE.ITEMID, UOMC.NUMERATOR, UOMC.DENOMINATOR, CASE WHEN UOMC.FROMUNITOFMEASURE = UOM_FROM.RECID THEN UOM_FROM.SYMBOL END AS 'FROM UNIT', CASE WHEN UOMC.TOUNITOFMEASURE = UOM_TO.RECID THEN UOM_TO.SYMBOL END AS 'TO UNIT' FROM ECORESPRODUCT JOIN INVENTTABLE ON INVENTTABLE.RECID = ECORESPRODUCT.RECID INNER JOIN UNITOFMEASURECONVERSION AS UOMC ON UOMC.PRODUCT = ECORESPRODUCT.RECID INNER JOIN UNITOFMEASURE AS UOM_FROM ON UOM_FROM.RECID = UOMC.FROMUNITOFMEASURE INNER JOIN UNITOFMEASURE AS UOM_TO ON UOM_TO.RECID = UOMC.TOUNITOFMEASURE WHERE INVENTTABLE.NAMEALIAS <> 'Discontinued' AND INVENTTABLE.COSTGROUPID = 'FG'