我需要一些帮助才能进行SQL查询
我有表'stock_exchange',它记录了四个不同商店/网站之间互换的股票
它记录
date,item_id,qty,price,total_price,from_site,to_site
现在我需要创建一个查询来运行其中一个商店/网站,这将返回其他三个商店之间发送和接收的股票的总价。
例如:Store1,Store2,Store3,Store4
如果我需要检查Store1,它应该返回:
商店名称_发送总数_收到的总数
商店2 _________ 90.90 _______ 50商店3 _________ 120 _______ 100.40
Store4_________400_______200
我试过自己,但只能得到已发送或收到的股票的总和。
以下是fiddle
修改
我把表更改为记录存储ID(1,2,3,4 ....)而不是存储别名(crw,chc,cal_rav ....),我接受的代码(回答)已经停止工作。我在代码中尝试了这个修正,按商店ID查找匹配的行,但不返回任何内容:
SELECT GREATEST(t2.name, t3.name) AS from_store,
LEAST(t2.name, t3.name) AS to_store,
SUM(CASE WHEN t2.name < t3.name THEN t1.total_price ELSE 0 END) AS total_sent,
SUM(CASE WHEN t2.name > t3.name THEN t1.total_price ELSE 0 END) AS total_received
FROM stock_exchange t1
INNER JOIN sites t2
ON t1.from_site = t2.id
INNER JOIN sites t3
ON t1.to_site = t3.id
GROUP BY GREATEST(t2.name, t3.name),
LEAST(t2.name, t3.name)
HAVING MAX(GREATEST(t2.id, t3.id)) = '1'
答案 0 :(得分:3)
在我看来,虽然有可能有更多更多的商店组合,但我更喜欢使用更简单的查询(通常甚至更快执行):
SELECT name, SUM(total_price) as total_sent_to FROM stock_exchange se
LEFT JOIN sites ON sites.alias = se.to_site
WHERE from_site = 'crw' GROUP BY from_site, to_site;
SELECT name, SUM(total_price) as total_received_from FROM stock_exchange se
LEFT JOIN sites ON sites.alias = se.from_site
WHERE to_site = 'crw' GROUP BY from_site, to_site;
结果:
...所以我会针对更大的数据量进行测试,并在生产中使用前比较解决方案。
计算总数:
SELECT *, (SELECT SUM(total_price)
FROM stock_exchange se
WHERE se.from_site = sites.alias
GROUP BY se.from_site)
as total_sent_sum,
(SELECT SUM(total_price)
FROM stock_exchange se
WHERE se.to_site = sites.alias
GROUP BY se.to_site)
as total_received_sum
FROM sites;
答案 1 :(得分:2)
这是一个查询,显示Cafe Rosewood向所有其他商店发送和接收的金额:
SELECT GREATEST(t2.name, t3.name) AS from_store,
LEAST(t2.name, t3.name) AS to_store,
SUM(CASE WHEN t2.name < t3.name THEN t1.total_price ELSE 0 END) AS total_sent,
SUM(CASE WHEN t2.name > t3.name THEN t1.total_price ELSE 0 END) AS total_received
FROM stock_exchange t1
INNER JOIN sites t2
ON t1.from_site = t2.alias
INNER JOIN sites t3
ON t1.to_site = t3.alias
GROUP BY GREATEST(t2.name, t3.name),
LEAST(t2.name, t3.name)
HAVING MAX(GREATEST(t2.name, t3.name)) = 'Cafe Rosewood'
如果要查看所有商店之间的交易,只需删除HAVING
子句即可。此查询采用了将GREATEST(from_site, to_site)
组合在一起的两个商店的技巧。