我有2个查询。第一个是找到净额,第二个是预算总和。我需要显示结果,包括来自差异表的商店名称和商店号。
以下是我查找总netamount的第一个查询:
SELECT sum(a.netamt) as netamt, b.store_name
FROM site_sales a JOIN site_store b ON b.storenum = a.storenum
WHERE a.busidate >= '2017-01-01' AND a.busidate <='2017-04-30'
GROUP BY a.storenum
第二个查询是查找总预算
SELECT
SUM(CASE WHEN c.busidate BETWEEN '2017-01' AND '2017-04' THEN c.budget ELSE 0 END) as budget,
b.store_name
FROM site_kpimthslsbgt c JOIN site_store b ON b.storenum = c.storenum
GROUP BY c.storenum
我需要结合这两个查询。输出的结果应该是 like this
答案 0 :(得分:0)
试试这个如果在你的个人查询中提取了多条记录,你最后还需要建立连接条件:
Select x.netamt, y.budget, y.store_name
from
(
SELECT sum(a.netamt) as netamt, b.store_name
FROM site_sales a JOIN site_store b ON b.storenum = a.storenum
WHERE a.busidate >= '2017-01-01' AND a.busidate <='2017-04-30'
GROUP BY a.storenum
) x
inner join
(
SELECT
SUM(CASE WHEN c.busidate BETWEEN '2017-01' AND '2017-04' THEN c.budget ELSE 0 END) as budget,
b.store_name
FROM site_kpimthslsbgt c JOIN site_store b ON b.storenum = c.storenum
GROUP BY c.storenum
) y
on x.store_name = y.store_name
答案 1 :(得分:0)
SELECT sum(a.netamt) as netamt,SUM(CASE WHEN c.busidate BETWEEN '2017-01' AND '2017-04' THEN c.budget ELSE 0 END) as budget,b.store_name
FROM site_store b
JOIN site_kpimthslsbgt c ON b.storenum = c.storenum
JOIN site_sales a ON b.storenum = a.storenum
GROUP BY b.storenum
尝试以上查询。
希望这会对你有所帮助。
答案 2 :(得分:0)
我认为这里有4种可能的情况,有销售和预算的商店,有销售但没有预算的商店,有预算但没有销售的商店,既没有销售也没有预算的商店。
鉴于
DROP TABLE IF EXISTS site_sales,site_budget;
CREATE TABLE site_sales(ID INT auto_increment primary key, site_id int, busidate date,amt int);
create table site_budget(ID INT auto_increment primary key, site_id int, busidate date,amt int);
insert into site_sales (site_id,busidate,amt) values
(1,'2017-04-01',10),(1,'2017-04-01',20),
(2,'2017-04-01',10);
insert into site_budget (site_id,busidate,amt) values
(1,'2017-04-01',200),
(3,'2017-04-01',100);
此查询
SELECT b.name,
sum(case when a.busidate between '2017-01-01' and '2017-04-30' then a.amt else 0 end) as netamt,
ifnull((select SUM(CASE WHEN c.busidate BETWEEN '2017-01-01' AND '2017-04-30' THEN c.amt ELSE 0 END) from site_budget c where b.id = c.site_id ),0) as budget
FROM sites b
left JOIN site_sales a ON b.id = a.site_id
GROUP BY b.id
结果
+--------+--------+--------+
| name | netamt | budget |
+--------+--------+--------+
| Store1 | 30 | 200 |
| Store2 | 10 | 0 |
| Store3 | 0 | 100 |
| Store4 | 0 | 0 |
+--------+--------+--------+
4 rows in set (0.00 sec)