我有三张桌子
Product
- ID_Product
UP
- ID_Product
- UP_SUM
DOWN
- ID_Product
- DOWN_SUM
对这三个表的查询创建一个列Total_SUM = [UP_SUM] - [DOWN_SUM]
问题是如果DOWN_SUM中没有值,则Total_SUM中没有结果。
EX。
UP
1 - 2
2 - 4
3 - 2
DOWN
1 - 1
3 - 1
TOTAL_SUM
(1) 1
(2) 4 -> value missing
(3) 1
事实上,我没有得到ID 2的价值。
如果不是isNULL,我如何使用语句来获取TOTAL_SUM中的所有值?实际上SQL查询是:
SELECT
Product.ID_Product,
UP.UP_SUM,
DOWN.DOWN_SUM,
[UP_SUM]-[DOWN_SUM] AS TOTAL_SUM,
FROM (PRODUCT INNER JOIN UP ON Product.ID_Product = UP.ID_Product)
INNER JOIN DOWN ON Product.ID_Product = DOWN.ID_Product;
答案 0 :(得分:0)
使用将使用值替换null的iif条件,并使用左外连接,因为普通连接正在过滤那些没有匹配的行。左连接将使它们保持值NULL
IIF(ISNULL(DOWN.DOWN_SUM),0,DOWN.DOWN_SUM)
SELECT
Product.ID_Product,
IIF(ISNULL(UP.UP_SUM),0,UP.UP_SUM),
IIF(ISNULL(DOWN.DOWN_SUM),0,DOWN.DOWN_SUM),
IIF(ISNULL(UP.UP_SUM),0,UP.UP_SUM)-IIF(ISNULL(DOWN.DOWN_SUM),0,DOWN.DOWN_SUM) AS TOTAL_SUM,
FROM (PRODUCT LEFT OUTER JOIN UP ON Product.ID_Product = UP.ID_Product)
LEFT OUTER JOIN DOWN ON Product.ID_Product = DOWN.ID_Product;