我最近使用此SQL语句的变体编写了一份报告:
select project.*, TF.*, TW.*, TR.*, TH.* from
(select sum(Quantity) as FQty from unitType where Type = 'F' group by type) TF,
(select sum(Quantity) as WQty from unitType where Type = 'W' group by type) TW,
(select sum(Quantity) as RQty from unitType where Type = 'R' group by type) TR,
(select sum(Quantity) as HQty from unitType where Type = 'H' group by type) TH
问题是,如果一个项目没有单元类型,那么该单元类型的sql语句将返回任何内容,然后使我的整个语句不返回任何内容。我一直试图找出如何让它返回0如果为null,但似乎没有什么对我有用。我已经尝试了Case,但它告诉我一些关于" isnull是一个无效的列名称"我也试过"如果存在"但这只会引发语法错误。
有什么建议吗?
答案 0 :(得分:0)
尝试用以下情况:
SELECT SUM(QUANTITY) AS FQTY FROM (SELECT CASE WHEN QUANTITY IS NULL THEN 0 ELSE QUANTITY END QUANTITY FROM....)
答案 1 :(得分:0)
试试这个:
OUTER APPLY (select sum(Quantity) as FQty from unitType where Type = 'F' group by type) TF
OUTER APPLY (select sum(Quantity) as WQty from unitType where Type = 'W' group by type) TW
OUTER APPLY (select sum(Quantity) as RQty from unitType where Type = 'R' group by type) TR
OUTER APPLY (select sum(Quantity) as HQty from unitType where Type = 'H' group by type) TH
由于您使用的CROSS JOIN,您有0行。行数为...* number of row of TF * number of row of TW *...
,并想象一个产品,其中一个数字为0,结果为0。