如何将sum(case)用作第二个表作为条件

时间:2016-01-17 14:21:04

标签: sql postgresql

这是我的疑问:

    select matricule,nom_ligne,count(num_ticket) as nbre_ticket, sum(prix) as moant,receveur, nom_gie, 
(SELECT SUM(CASE WHEN depense.id_bus = 1 THEN depense.montant ELSE 0 END) AS NbrARRNP from depense) as tot,
receveur, nom_gie from journal_recettes
group by matricule,nom_ligne,receveur, nom_gie

我得到了这个结果: Results 但我需要的是使用这个条件:

CASE WHEN depense.id_bus = journal_recettes.id_bus THEN depense.montant ELSE 0 END

但是当我尝试时,我得到了这个错误:

Error

4 个答案:

答案 0 :(得分:0)

通过加入id_bus

上的两个表,考虑修改您的查询,如下所示
select j.matricule,
j.nom_ligne,
count(j.num_ticket) as nbre_ticket, 
sum(j.prix) as moant,
j.receveur, 
j.nom_gie, 
SUM(d.id_bus) AS NbrARRNP
from journal_recettes j
join depense d on d.id_bus = j.id_bus
group by j.matricule,
j.nom_ligne,
j.receveur, 
j.nom_gie;

答案 1 :(得分:0)

您正在寻找相关子查询。这通常在where子句中处理:

select matricule, nom_ligne, count(num_ticket) as nbre_ticket,
       sum(prix) as moant, receveur, nom_gie, 
       (select SUM(d.montant) AS NbrARRNP
        from depense d
        where d.id_bus = jr.id_bus
       ) as tot,
       receveur, nom_gie
from journal_recettes jr 
group by matricule, nom_ligne, receveur, nom_gie;

在这种情况下,您可能会遇到问题,因为相关条件不是group by键。我不确定Postgres是否支持这种结构。如果这是一个问题,最简单的解决方案是在id_bus中包含group by,但如果没有样本数据,我不确定在这种情况下是否有效。

答案 2 :(得分:0)

假设您正在使用id_bus进行连接,您可以使用公用表表达式(http://www.postgresql.org/docs/9.5/static/queries-with.html

Function lptmIn
    Set o = New lptm

    Do
        o.inputstr3  = InputBox("enter names")
        o.grpString1 = Split(o.inputstr3, ",")

        o.inputstr4  = InputBox("enter loss %")
        o.grpString2 = Split(o.inputstr4, ",")
    Loop Until UBound(o.grpString1) = UBound(o.grpString2)

    Set lptmIn = o
End Function 

Set obj = lptmIn
For i=0 To UBound(obj.grpString1)
  lptmstr = lptmstr & obj.grpString1(i)  + obj.grpString2(i)
Next

答案 3 :(得分:0)

非常感谢所有人。 我发布了我的最终解决方案:

select p1.matricule,p1.nom_ligne,
Count(p1.num_ticket) as nbre_ticket, Sum(p1.prix) as montant, 
(select sum(montant) as tot from depense p2
where date_trunc('day',p2.date_depense) = date_trunc('day',p1.date_vendu)  
group by date_depense) som_depense  ,
(Sum(p1.prix) -((select sum(montant) as tot from depense p3
where date_trunc('day',p3.date_depense) = date_trunc('day',p1.date_vendu)  
group by date_depense) ) ) net_reverse ,to_char(p1.date_vendu,'YYYYMMDD'),
p1.receveur, p1.nom_gie, id_line
    from journal_recettes p1
    group by 
    matricule,nom_ligne, date_vendu,receveur,nom_gie, id_line

它的工作也是如此。