SQL:两列计算第一列和第二列的第三列总和

时间:2018-04-03 11:04:05

标签: sql oracle count sum

我试图创建两个计数不同项目的列然后在第三列SUM up第1列和第2列。任何帮助表示赞赏!谢谢!

SELECT 
    (SELECT COUNT(ecarrno) Conventional FROM L16T3
     WHERE (l16lcode = 46) AND
        (l46adr IN ('680', '657','693','623','639','704','644','679'))),
    (SELECT COUNT(admunit) Auto FROM L16T3
    WHERE (admunit= 16AP) AND
        (l46adr IN ('611','618','637','638'))),
    SUM (COUNT(ecarrno) + COUNT(admunit))
    FROM L16T3
    AND DATREG >= @('START DATE',datreg)  
    AND DATREG <= @('END DATE',datreg)
ORDER BY datreg 
DESC,l16seqno DESC

2 个答案:

答案 0 :(得分:0)

您可以使用条件聚合和子查询。查询看起来像这样:

SELECT Conventional, Auto, (Conventional + Auto)
FROM (SELECT SUM(CASE WHEN l16lcode = 46 AND l46adr IN ('680', '657', '693', '623', '639', '704', '644', '679')
                      THEN 1 ELSE 0
                 END) as Conventional,
             SUM(CASE WHEN admunit = '16AP' AND l46adr IN ('611', '618', '637', '638')
                      THEN 1 ELSE 0
                 END) as Auto
      FROM L16T3 l
     WHERE DATREG >= @('START DATE', datreg)   AND DATREG <= @('END DATE', datreg)     
    ) l
ORDER BY datreg ;

答案 1 :(得分:0)

使用条件聚合

SELECT sum(case when l16lcode = 46 and l46adr IN ('680', '657','693','623','639','704','644','679') then 1 else 0 end )col1, 
       sum(case when admunit= 16AP and l46adr IN ('611','618','637','638') then 1 else 0 end ) col2, 
    sum(case when l16lcode = 46 and l46adr IN ('680', '657','693','623','639','704','644','679') then 1 else 0 end )+
       sum(case when admunit= 16AP and l46adr IN ('611','618','637','638') then 1 else 0 end ) col3

        FROM L16T3
        where DATREG >= @('START DATE',datreg)  
        AND DATREG <= @('END DATE',datreg)