我计划做的是它会从两个表(tblshoes,tblpants)获取过去一个月的所有记录,并计算发生了多少订单,因为这将在谷歌图表折线图上使用我试图获得所有数据从7月30日到1日
SELECT COUNT(*) AS shoeorder, EXTRACT(DAY FROM tlDate) as pdate
FROM tblshoes
WHERE tlDate >= CURRENT_DATE - INTERVAL 1 MONTH
GROUP BY EXTRACT(DAY FROM tlDate)
以下是我的表格:
tblshoes
sname tlDate
Name Here 2017-07-15
Name Again 2017-07-14
Name again and again 2017-07-13
Name im tired 2017-07-15
Name of a patient 2017-07-10
.....
tblpants
pname tlDate
Name Here 2017-07-15
Name Again 2017-07-14
Name again and again 2017-07-13
Name im tired 2017-07-15
Name of a patient 2017-07-10
结果:
shoeorder pdate
2 15
1 14
1 13
1 10
我想要的是什么:
shoeorder pdate pantorder
0 30 0
0 29 0
0 28 0
0 27 0
0 26 0
0 25 0
0 24 0
0 23 0
0 22 0
0 21 0
0 20 0
0 19 0
0 18 0
0 17 0
0 16 0
2 15 2
1 14 1
1 13 1
0 12 0
0 11 0
1 10 1
0 9 0
0 8 0
0 7 0
0 6 0
0 5 0
0 4 0
0 3 0
0 2 0
0 1 0
答案 0 :(得分:0)
SELECT COUNT(*) AS shoeorder, EXTRACT(DAY FROM tlDate) as pdate
FROM (select tlDate from tblshoes
union all
select tlDate from tblpants) sub
WHERE tlDate >= CURRENT_DATE - INTERVAL 1 MONTH
GROUP BY EXTRACT(DAY FROM tlDate)
猜猜你应该将两个表合并,然后将group by应用于结果查询
更新:然后你需要一个填满所有日期的表(每天)。使用该表并左键加入查询。
SELECT COUNT(*) AS shoeorder, EXTRACT(DAY FROM adt.tlDate) as pdate
FROM all_days_table adt
LEFT JOIN (select tlDate from tblshoes
union all
select tlDate from tblpants) sub ON adt.tlDate = sub.tlDate
WHERE tlDate >= CURRENT_DATE - INTERVAL 1 MONTH
GROUP BY EXTRACT(DAY FROM adt.tlDate)
答案 1 :(得分:0)
您需要使用完全外部联接...
select
coalesce(a.shoeorder, 0) as shoeorder
,coalesce(a.pdate, b.pdate) as pdate
,coalesce(b.pantorder, 0) as pantorder
from (
SELECT COUNT(*) AS shoeorder, EXTRACT(DAY FROM tlDate) as pdate
FROM tblshoes
WHERE tlDate >= CURRENT_DATE - INTERVAL 1 MONTH
GROUP BY EXTRACT(DAY FROM tlDate)
) a
left join (
SELECT COUNT(*) AS pantorder, EXTRACT(DAY FROM tlDate) as pdate
FROM tblpants
WHERE tlDate >= CURRENT_DATE - INTERVAL 1 MONTH
GROUP BY EXTRACT(DAY FROM tlDate)
) b
on a.pdate = b.pdate
union
select
coalesce(a.shoeorder, 0) as shoeorder
,coalesce(a.pdate, b.pdate) as pdate
,coalesce(b.pantorder, 0) as pantorder
from (
SELECT COUNT(*) AS shoeorder, EXTRACT(DAY FROM tlDate) as pdate
FROM tblshoes
WHERE tlDate >= CURRENT_DATE - INTERVAL 1 MONTH
GROUP BY EXTRACT(DAY FROM tlDate)
) a
right join (
SELECT COUNT(*) AS pantorder, EXTRACT(DAY FROM tlDate) as pdate
FROM tblpants
WHERE tlDate >= CURRENT_DATE - INTERVAL 1 MONTH
GROUP BY EXTRACT(DAY FROM tlDate)
) b
on a.pdate = b.pdate