2012-11-02 29 views
4

我有一个像SQL查询中的每个元素如下:将行添加到SQL查询的WHERE序列

SELECT store_id, SUM(quantity_sold) AS count 
FROM sales_table 
WHERE store_id IN ('Store1', 'Store2', 'Store3') 
GROUP BY store_id; 

这将返回每个有sales_table行店一排,但不会返回一行那些不。我想要的是每个商店一行,如果它没有记录,则为0count

我该如何做到这一点,假设我无法访问stores表?

+0

你有“商店”表吗? – climbage

+0

否---或者说,它在不同的DBMS中。 –

回答

7
with stores (store_id) as (
    values ('Store1'), ('Store2'), ('Store3') 
) 
select st.store_id, 
     sum(sal.quantity_sold) as cnt 
from stores st 
    left join sales_table sal on sal.store_id = st.store_id 
group by st.store_id; 

如果你有一个stores表,后来干脆外部联接到一个,而不是“做一补”使用公共表表达式(with ..)。

这也可以写成不CTE(公共表表达式):

select st.store_id, 
     sum(sal.quantity_sold) as cnt 
from (
    values ('Store1'), ('Store2'), ('Store3') 
) st 
    left join sales_table sal on sal.store_id = st.store_id 
group by st.store_id; 

(但我发现CTE的版本更容易理解)

+1

'values('Store1','Store2','Store3')'将返回一列三列,而不是三列,每列一列。 – lanzz

+0

+1。 (顺便说一句,即使没有实际的'stores'表,你也可以定义一个子查询为'(SELECT'Store1'AS store_id UNION SELECT'Store2'UNION SELECT'Store3')st'。这是否比WITH更好/更清晰'条款是一个意见的问题。)*编辑:* +1收回等待您的修复lanzz的评论。 – ruakh

+0

postgresql有CTE吗? –

0

您可以使用unnest()来从数组元素的行。

SELECT store, sum(sales_table.quantity_sold) AS count 
FROM unnest(ARRAY['Store1', 'Store2', 'Store3']) AS store 
LEFT JOIN sales_table ON (sales_table.store_id = store) 
GROUP BY store;