加入相同的表重复行

时间:2017-02-06 10:45:19

标签: mysql sql join

我正在尝试在查询中加入同一个表,但我得到重复的行。

我想得到的是一个列,其中包含年度发票的总和,以及每个客户的每个三个月的列。

以下是查询的简化版本:

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'

然后应该是:

client name       Total         T1
    A            1382.17      123.56
    B           2,557.32     2,557.32

当我手动检查其中一个时,结果应该是3.000左右,我得到81.000

我尝试使用sum(distinct total.totdoc)并且它适用于某些(具有不同总数的那些),但重复的那些会丢失。

同样,这是一个简化的例子,如果有任何不清楚的地方,请询问。

谢谢!

2 个答案:

答案 0 :(得分:0)

我认为您不应该加入发票T1,因为这样,您将获得此重复记录,只有一个连接就足够了。如果您看到查询而不是选择满足第一个连接的行,则第二个连接将选择相同的行。我认为您需要为每个客户分别查询年度和Trimester的发票总额。

喜欢

select client.name, sum(total.totdoc) as TOTAL, sum(total.totdoc) as T1 
 from client
 join invoices total
      on total.idclient=client.idclient
 where total.date between '01/01/2016' and '30/06/2016'
  and total.date between '01/01/2016' and '31/12/2016'

答案 1 :(得分:0)

我认为你只想要条件聚合。像这样:

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;