SQL嵌入式案例

时间:2014-10-22 20:22:52

标签: sql case

我是Sql的新手。没有IF条件的那些表的逻辑总是让我烦恼。我有一个像这样的表(MyTable):

ID ProjectID ClassType  ClassYear Amount
1   1   A   2014    0.00
2   1   A   2014    0.00
3   1   B   2014    300.00
5   1   B   2013    100.00
6   1   C   2015    200.00
7   1   A   2013    0.00
8   1   B   2015    200.00
9   1   B   2014    500.00
11  1   B   2015    230.00
....

我的原始代码如下工作正常:

Some code 
from 
(
    Select projectID, sum(currentyear) as CurrentYear, sum(prioryear) as PriorYear, sum(postyear) as PostYear
    from 
        (select ProjectID, 
            case when Classyear = 2014 then Amount else 0 end as currentyear,
            case when ClassYear <2014 then Amount else 0 end as prioryear,
            case when ClassYear > 2014 then Amount else 0 end as postyear 
            from MyTable
            where classtype = 'A'
         ) as subtable
    group by subtable.ProjectID
)

现在我想为上面的classtype添加更多选项,但无法弄清楚如何。逻辑应该是:

如果项目中classtype A的总金额为0(换句话说,这三个数字都是0)那么where条件应该更改为classtype ='B'。如果classtype B仍然全为0,则使用classtype C.(如果C仍为0,则可以。)

我应该把新的情况放在哪里?

1 个答案:

答案 0 :(得分:1)

我们可以使用GROUP BY为每个类类型获取总数,然后过滤适当的值。

 SELECT * 
FROM
(
select *, ROW_NUMBER() over ( partition by projectId order by classType) as seq FROM
(
    Select projectID, classType, sum(Amount) as Total, 
           sum(case when Classyear = 2014 then Amount else 0 end) as CurrentYear, 
           sum(case when ClassYear <2014 then Amount else 0 end) as PriorYear, 
           sum( case when ClassYear > 2014 then Amount else 0 end) as PostYear

    from 
    myTable
    group by ProjectID, classType
) T
Where (T.Total >0 and classType <> 'C') or classType ='C' 
) C
where seq =1