我现在要查询两个表,使用左连接,首先使用主表中的按日期分组,日期根据星期分组,现在我也想使用相同的日期分组联接的联接表。如何查询呢? 现在我正在这样做
select
case
when order.time BETWEEN '2018-7-27' and '2018-8-3' then '7.27-8.2'
when order.time BETWEEN '2018-8-3' and '2018-8-10' then '8.3-8.9'
else "--" end ptime,
payment.uid, payment.time
from order
left join
(select uid, time, from payment where create_time between '2018-7-27' and '2018-8-10') payment on payment.uid = order.uid
where order.time between '2018-7-13' and '2018-8-10'
+----------+-------+-----------------------+
| date | uid | time |
+----------+-------+-----------------------+
| 7.27-8.2 | 42 | 2018-07-27 22:08:22 |
| 7.27-8.2 | 42 | 2018-07-27 22:08:22 |
| 8.3-8.9 | 50 | 2018-08-04 14:19:00 |
| 8.3-8.9 | 50 | 2018-08-04 14:19:00 |
| 8.3-8.9 | 76 | 2018-07-28 14:20:00 |
| 8.3-8.9 | 76 | 2018-07-28 14:12:00 |
| 8.3-8.9 | 76 | 2018-07-28 13:12:00 |
| 8.3-8.9 | 88 | 2018-07-28 19:29:00 |
| 8.3-8.9 | 98 | 2018-08-09 14:39:00 |
+----------+-------+-----------------------+
除了输出:
+----------+-------+-----+
| date | uid | time|
+----------+-------+-----+
| 7.27-8.2 | 42 | 2 |
| 8.3-8.9 | 50 | 2 |
| 8.3-8.9 | 76 | 3 |
| 8.3-8.9 | 88 | 0 |
| 8.3-8.9 | 98 | 1 |
+----------+-------+-----+
但是,这样,付款时间不会根据订单日期进行分组。 分组规则仍在订单表上。
如何将日期分组应用于两个表,并且对工资表重复数据删除进行相同的分组?非常感谢你!
答案 0 :(得分:0)
这是我的解决方案:
select p1.ptime, p2.uid, count(p2.uid) (
select
case
when order.time BETWEEN '2018-7-27' and '2018-8-3' then '7.27-8.2'
when order.time BETWEEN '2018-8-3' and '2018-8-10' then '8.3-8.9'
else "--" end ptime
from order
where order.time between '2018-7-13' and '2018-8-10' group by ptime) p1
left join
(select
case
when payment.time BETWEEN '2018-7-27' and '2018-8-3' then '7.27-8.2'
when payment.time BETWEEN '2018-8-3' and '2018-8-10' then '8.3-8.9'
else "--" end p2time,
count(payment.uid) uid_cnt
from order
left join
(select uid, time, from payment where create_time between '2018-7-27' and
'2018-8-10') payment on payment.uid = order.uid
where order.time between '2018-7-13' and '2018-8-10' group by p2time) p2
on p2.p2time = p1.ptime
答案 1 :(得分:-1)
您只需要聚合函数count
select uid,date(ptime) as date,count(payment.time) as time
from
( select
case
when order.time BETWEEN '2018-7-27' and '2018-8-3' then '7.27-8.2'
when order.time BETWEEN '2018-8-3' and '2018-8-10' then '8.3-8.9'
else "--" end ptime,
payment.uid, payment.time
from order
left join
(select uid, time, from payment where create_time between '2018-7-27' and '2018-8-10') payment on payment.uid = order.uid
where order.time between '2018-7-13' and '2018-8-10'
) as t group by uid,date(ptime)