我相信stackoverflow已经有了答案,但我找不到合适的关键字。所以请帮忙。
表销售如下所示:
state | sales-representative | product | sales
NY | Mike B. | prod-A | 90
FL | David J. | prod-B | 120
FL | Mike B. | prod-A | 15
我需要获得此类销售代表的总销售额。 Mike B.的预期结果看看:
state | product | sales
NY | prod-A | 90
FL | prod-A | 15
NY | prod-B | 0 <--How can I get this record as well?
FL | prod-B | 0
常规总和查询返回前2个记录。我怎样才能获得最后2条记录?
select state, product, sum(sales)
from sales
where sales-representative = 'Mike B.'
group by state, product
答案 0 :(得分:1)
SELECT ss.state, sp.product, SUM(sr.sales)
FROM (SELECT DISTINCT state FROM sales) AS ss
CROSS JOIN (SELECT DISTINCT product FROM sales) AS sp
LEFT JOIN sales AS r
AS sr ON ss.state = s.state
AND sp.product = s.product
AND r.`sales-representative` = 'Mike B.'
GROUP BY ss.state, sp.product;
交叉连接可以为您提供州和产品的每种组合,左连接可以获得指定代表的相关销售。
答案 1 :(得分:0)
您可以在子查询上使用左连接来表示陈述和产品
select t.state, t.product, sum(sales)
from table1
left join (
select t1.state, t2.product
from t1
cross join (
select product
from t1
) t2
) t on t.state = table1.state and t.product = table1.product
grooup by t.state, t.product