我有2个包含以下数据的表:
表1(dummy_daily)
Entry storenum busidate daily_budget
1 1 2017-07-01 4000
2 1 2017-07-02 3500
3 1 2017-07-03 2000
4 1 2017-07-04 6000
5 1 2017-07-05 1500
表2(site_labour)
Lab_id storenum busidate lab_hour
1123 1 2017-07-01 128
1124 1 2017-07-02 103
1125 1 2017-07-03 114
1126 1 2017-07-04 108
1127 1 2017-07-05 118
这是我当前的查询,用于合并具有相同日期的2个表格,以提供daily_budget
和lab_hour
的结果
QUERY:
SELECT
a.daily_budget as Ideal, c.lab_hour as Actual,
b.store_name, b.storenum,a.busidate
FROM dummy_daily a JOIN site_store b ON b.storenum=a.storenum JOIN
site_labour c ON b.storenum=c.storenum
WHERE b.storenum='1' AND
(CASE WHEN c.busidate BETWEEN '2017-07-01' AND '2017-07-05' THEN c.lab_hour ELSE 0 END)
AND (CASE WHEN a.busidate
BETWEEN '2017-07-01' AND '2017-07-05' THEN a.daily_budget ELSE 0 END)
但是我当前的查询给出了错误的结果:
当前查询的错误结果
Ideal Actual storenum busidate
4000 128 1 2017-07-01
3500 128 1 2017-07-02
2000 128 1 2017-07-03
6000 128 1 2017-07-04
1500 103 1 2017-07-05
4000 103 1 2017-07-01
3500 103 1 2017-07-02
2000 103 1 2017-07-03
6000 103 1 2017-07-04
1500 103 1 2017-07-05
此数据将持续到实际118结束
预期结果
Ideal Actual storenum busidate
4000 128 1 2017-07-01
3500 103 1 2017-07-02
2000 114 1 2017-07-03
6000 108 1 2017-07-04
1500 118 1 2017-07-05
答案 0 :(得分:0)
让我们尝试下面的SQL:
SELECT
a.daily_budget as Ideal, c.lab_hour as Actual,
b.store_name, b.storenum,a.busidate
FROM dummy_daily a JOIN site_store b ON b.storenum=a.storenum AND b.busidate=a.busidate JOIN
site_labour c ON b.storenum=c.storenum AND b.busidate=c.busidate
WHERE b.storenum='1' AND
(CASE WHEN c.busidate BETWEEN '2017-07-01' AND '2017-07-05' THEN c.lab_hour ELSE 0 END)
AND (CASE WHEN a.busidate
BETWEEN '2017-07-01' AND '2017-07-05' THEN a.daily_budget ELSE 0 END)
答案 1 :(得分:0)
你错过了另外一张桌子,因此制造逻辑会造成混乱, 根据我的理解,我创建了一个SELECT语句。请试试这个: -
SELECT
dummy_daily.daily_budget as Ideal, site_labour.lab_hour as Actual,
site_store.store_name, site_store.storenum, dummy_daily.busidate
FROM dummy_daily
JOIN site_store
ON dummy_daily.storenum = site_store.storenum
JOIN site_labour
ON dummy_daily.storenum = site_labour.storenum
WHERE (dummy_daily.storenum = 1)
AND (dummy_daily.busidate BETWEEN '2017-07-01' AND '2017-07-05')
AND (site_labour.busidate BETWEEN '2017-07-01' AND '2017-07-05')
AND (dummy_daily.busidate = site_labour.busidate);