sql sum案例没有总结

时间:2016-12-09 09:47:48

标签: sql sum case

我试图编写一个脚本,总结每个代码的每个代码的总金额,不包括某些批次类型。

脚本运行但不汇总每个代码的数据。我做错了什么?

如果有更好的方法来编写脚本,也欢迎提供反馈。

由于

SELECT 
(CASE
    when DET_ledger = 'NL' and det_nominaldr = ''  then det_nominalcr
    when DET_ledger = 'NL' and det_nominalcr = ''  then det_nominaldr
    else  det_analysis
    end ) as Code,
DET_YEAR,
DET_PERIODNUMBR,
sum(CASE
    when DET_ledger = 'NL' and det_nominaldr = ''  then -1* det_nett
    when DET_ledger = 'PL' and det_type = 'CRN'   then -1* det_nett 
        else  det_nett
    end) as Net
FROM SL_PL_NL_DETAIL
where det_year = 'C'
and det_periodnumbr = '07'
and (det_nominalcr like '617%' or det_nominaldr like '617%')
and det_primary not in 
    (select det_primary
     from sl_pl_nl_detail
     where det_ledger in ('PL','SL')
     and det_batch_flag = 1)
group by det_nominaldr, det_nominalcr, det_nett, det_ledger, det_year, det_periodnumbr, det_analysis, det_type

3 个答案:

答案 0 :(得分:0)

我认为你在分组条款中不需要det_nett列试试这个

ListView

答案 1 :(得分:0)

如果这是Oracle,因为你没有指定你的DBMS,试试这个(在oracle你可以很容易地在group by中提到这个案例,我不确定其他数据库):

SELECT 
(CASE
    when DET_ledger = 'NL' and det_nominaldr = ''  then det_nominalcr
    when DET_ledger = 'NL' and det_nominalcr = ''  then det_nominaldr
    else  det_analysis
    end ) as Code,
DET_YEAR,
DET_PERIODNUMBR,
sum(CASE
    when DET_ledger = 'NL' and det_nominaldr = ''  then -1* det_nett
    when DET_ledger = 'PL' and det_type = 'CRN'   then -1* det_nett 
        else  det_nett
    end) as Net
FROM SL_PL_NL_DETAIL
where det_year = 'C'
and det_periodnumbr = '07'
and (det_nominalcr like '617%' or det_nominaldr like '617%')
and det_primary not in 
    (select det_primary
     from sl_pl_nl_detail
     where det_ledger in ('PL','SL')
     and det_batch_flag = 1)
group by CASE  when DET_ledger = 'NL' and det_nominaldr = ''  then det_nominalcr  
               when DET_ledger = 'NL' and det_nominalcr = ''  then det_nominaldr
               else  det_analysis  end,
         DET_YEAR,
         DET_PERIODNUMBR

答案 2 :(得分:0)

通过将原始查询包装在派生表GROUP BY中,保存一些输入结果:

select Code, DET_YEAR, DET_PERIODNUMBR, SUM(Net)
FROM
(
    SELECT (CASE
            when DET_ledger = 'NL' and det_nominaldr = ''  then det_nominalcr
            when DET_ledger = 'NL' and det_nominalcr = ''  then det_nominaldr
            else  det_analysis
            end) as Code,
           DET_YEAR,
           DET_PERIODNUMBR,
           (CASE
            when DET_ledger = 'NL' and det_nominaldr = ''  then -1* det_nett
            when DET_ledger = 'PL' and det_type = 'CRN'   then -1* det_nett 
            else  det_nett
            end) as Net
    FROM SL_PL_NL_DETAIL
    where det_year = 'C'
      and det_periodnumbr = '07'
      and (det_nominalcr like '617%' or det_nominaldr like '617%')
      and det_primary not in 
        (select det_primary
         from sl_pl_nl_detail
         where det_ledger in ('PL','SL')
         and det_batch_flag = 1)
) dt
group by Code, DET_YEAR, DET_PERIODNUMBR