我有两个表Received和Issued,它们与ID字段有关。我试图使用以下查询来获取结果,它只在两个表都有值时才有效。但是当一个表为空时,查询返回NULL值。我需要帮助
SELECT
c.vaccine_id,
c.name,
SUM(QRecived-IsuedQuan) Quantity
FROM
vaccine c
LEFT OUTER JOIN (
SELECT SUM(quantity_recieved) QRecived,vaccine_id from vaccine_detail group by vaccine_id
) a ON a.vaccine_id=c.vaccine_id
LEFT OUTER JOIN (
select SUM(issued_quantity) IsuedQuan,vaccine_id from issued_item group by vaccine_id
) b ON b.vaccine_id=a.vaccine_id "
GROUP BY c.vaccine_name,c.vaccine_id ";
注意:上面的查询将在SQLITE中运行,这只是为了通知您SQLLITE不支持RIGHT&完全加入
答案 0 :(得分:3)
您不需要外部group by
。问题是,当没有匹配时,值为NULL
,因此您需要将其替换为其他值:
SELECT v.vaccine_id, v.name,
coalesce(r.QReceived, 0) - coalesce(i.IssuedQuan, 0) as Quantity
FROM vaccine v LEFT OUTER JOIN
(SELECT SUM(quantity_recieved) as QReceived, vaccine_id
FROM vaccine_detail
GROUP BY vaccine_id
) r
ON r.vaccine_id = v.vaccine_id LEFT OUTER JOIN
(SELECT SUM(issued_quantity) as IssuedQuan, vaccine_id
FROM issued_item
GROUP BY vaccine_id
) i
ON i.vaccine_id = v.vaccine_id;
您可以使用isnull()
或coalesce()
,但coalesce()
是ANSI标准功能。
答案 1 :(得分:0)
SELECT c.vaccine_id,
c.name,
SUM(IfNull(QRecived,0) - IfNull(IsuedQuan,0)) Quantity
FROM vaccine c
....
应该照顾好。