2017-02-06 9 views
1

クエリで同じテーブルに参加しようとしていますが、重複する行があります。同じテーブルに重複する行を結合する

私が得たいのは、年間の請求書の合計と、各クライアントの各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 

私が手動でそれらの1つをチェックすると、結果は約3.000になるはずです。私は81.000に近づいています

私はsum(distinct total.totdoc)で試してみましたが、いくつか(合計が異なるもの)で動作しますが、繰り返されるものは紛失します。

これもまた単純化された例なので、不明な点がある場合は質問してください。

ありがとうございます!

+0

はあなたが欠けていると考えて... client.name – Veljko89

+0

でグループここに行方不明の引用があります: ''01/01/2016' の間t1.dateと30/06/2016''は、このような何か – McNets

+0

いくつかのサンプルデータを提供することができます –

答えて

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; 
+0

これは素晴らしいです!私はあなたがSQLでこれのような条件文を使うことができるのか分からなかった。 ありがとうございます、あなたは命を救う人です! (ちょうどsidenoteとして、having節であなたはi.totdoc:Pを合計しなければなりません) – Frankie

0

私は、請求書T1と一緒に参加すべきではないと思うので、この重複したレコードを取得しています.1回の参加で十分です。最初の結合を満たす行が選択された後に同じ行が2番目の結合によって選択されるようにクエリを参照すると、私はあなたが1年の請求書の合計と各クライアントの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' 
+0

私は提供した例と異なる何も表示されません – Frankie

+0

これはいくつかの違いをもたらすことを期待してください –

+0

T1は宣言されていないので、t1.dateまたはt1.totdocを見つけることができません – Frankie

関連する問題