我试图在查询中加入同一个表,但我得到了重复的行。
我想要得到的是包含当年发票总和的列,以及每个客户每个 Trimester 的列。
这是查询的简化版本:
select client.name, sum(total.totdoc) as TOTAL, sum(t1.totdoc) as T1
from client
join invoices total
on total.idclient=client.idclient
join invoices t1
on t1.idclient=total.idclient
where t1.date between '01/01/2016' and '30/03/2016'
and total.date between '01/01/2016' and '31/12/2016'
group by client.name
having sum(total.income) > '1000'
示例数据(客户端只是 idclient 和名称):
Invoices table
Idclient totdoc date
1 123.56 '01/02/2016'
1 1,258.61 '05/05/2016'
2 2,557.32 '07/03/2016'
3 123.56 '30/11/2016'
Outpot 应该是:
client name Total T1
A 1382.17 123.56
B 2,557.32 2,557.32
当我手动检查其中一个时,结果应该在 3.000 左右,而我得到的是 81.000 左右
我尝试使用 sum(distinct total.totdoc)
并且它适用于某些(总计不同的),但重复的那些会丢失。
同样,这是一个简化的示例,所以如果有任何不清楚的地方,请询问。
谢谢!
最佳答案
我认为您只需要条件聚合。像这样:
select c.name, sum(i.totdoc) as total,
sum(case when month(date) in (1, 2, 3) then i.totdoc end) as q1,
sum(case when month(date) in (4, 5, 6) then i.totdoc end) as q2,
sum(case when month(date) in (7, 8, 9) then i.totdoc end) as q3,
sum(case when month(date) in (10, 11, 12) then i.totdoc end) as q4
from client c join
invoices i
on i.idclient = c.idclient
where i.date >= '2016-01-01' and i.date < '2017-01-01'
group by c.name
having sum(i.income) > 1000;
关于mysql - 加入同一张表的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42065856/