即使另一个表中的相应值为NULL,也要从另一个表中选择所有数据

时间:2016-08-12 15:12:36

标签: sql-server

我有这个问题:

ggplot(df, aes(x = 1,y = name, fill = value)) + 
  geom_tile() + 
  ylab("") +
  scale_fill_gradient(low='red', high='blue')

我是SQL SERVER的初学者。此查询仅显示具有相应SELECT city.CITY_NAME, SUM(case when c.CUSTOMER_ID=o.CUSTOMER_ID and o.ORDER_ID=od.ORDER_ID then od.TOTAL_AMT_PER_ITEM else 0 end) AS TOTAL_AMT_PER_ITEM FROM [ORDER] o INNER JOIN ORDER_DETAILS od ON o.ORDER_ID = od.ORDER_ID INNER JOIN CUSTOMER c ON o.CUSTOMER_ID = c.CUSTOMER_ID INNER JOIN CUSTOMER_ADDRESS ca ON ca.CUSTOMER_ID = c.CUSTOMER_ID INNER JOIN CITY city ON ca.CITY_ID = city.CITY_ID GROUP BY city.CITY_NAME 值的CITY_NAME。我需要的是显示数据库中的所有TOTAL_AMT_PER_ITEM,即使它们的对应值为NULL。这有什么用?有人可以帮我吗?谢谢!

2 个答案:

答案 0 :(得分:2)

我改变了联接的顺序,也许是帮助。

  • 您从CITY开始,因为它是GROUP BY的来源,并尝试查看是否有CUSTOMER_ADDRESS
    • 我想如果是新店,你可以有0个顾客。
  • 然后INNER JOIN因为方向不能单独存在,它们属于客户
  • 然后LEFT JOIN,因为CUSTOMER可能会或可能没有[ORDERS]
  • 然后INNER JOIN,因为每个[ORDERS]都有[ORDER DETAILS]
  • 最后SUM(od.TOTAL_AMT_PER_ITEM)表中的JOIN,这可以得到一些NULL's,因此您需要包含COALESCE

    SELECT city.CITY_NAME, 
           COALESCE(SUM(od.TOTAL_AMT_PER_ITEM) , 0) as TOTAL_AMT_PER_ITEM
    FROM [CITY]  
    LEFT JOIN [CUSTOMER_ADDRESS] ca
           ON ca.CITY_ID = [CITY].CITY_ID
    INNER JOIN CUSTOMER c
       ON ca.CUSTOMER_ID = c.CUSTOMER_ID
    LEFT JOIN [ORDER] o
       ON o.CUSTOMER_ID = c.CUSTOMER_ID
    INNER JOIN ORDER_DETAILS od
       ON o.ORDER_ID = od.ORDER_ID       
    GROUP BY [CITY].CITY_NAME
    

顺便说一下,您应该将表[Order]的名称更改为[Orders],因为订单是一个保留字,可能会导致问题。

一般情况下,我更喜欢使用复数名称表,因为它是一个保存多个类型

的实体
  • CITIES而不是CITY
  • CUSTOMERS的客户
  • ORDER_DETAILS已经是复数,所以尽量保持一致。

答案 1 :(得分:1)

SELECT 
    city.CITY_NAME, 
    SUM(od.TOTAL_AMT_PER_ITEM) AS TOTAL_AMT_PER_ITEM
FROM 
    CUSTOMER c
INNER JOIN 
    CUSTOMER_ADDRESS ca
    ON ca.CUSTOMER_ID = c.CUSTOMER_ID
INNER JOIN 
    CITY city
    ON ca.CITY_ID = city.CITY_ID
LEFT JOIN
    [ORDER] o
    ON o.CUSTOMER_ID = c.CUSTOMER_ID
LEFT JOIN
    ORDER_DETAILS 
    ON o.ORDER_ID = od.ORDER_ID
GROUP BY city.CITY_NAME