SQL sum列基于列"类型"

时间:2018-03-13 17:37:20

标签: sql

我有一个像这样的观点

col1 col2 col3 year class type
1    3    4    2017 A     1
4    5    7    2017 A     2
3    4    2    2017 A     3
3    1    1    2017 A     4
1    1    1    2017 B     1
0    0    2    2017 B     2
2    2    0    2017 B     3

我想要的是根据上面的内容创建一个新视图,如果"键入"我想要对同一年的列进行求和。不是1.如果type = 1,则新值为" yes",如果键入!= 1" no"。

col1 col2 col3 year class new
1    3    4    2017 A     yes
10   10   10   2017 A     no
1    1    1    2017 B     yes
2    2    2    2017 B     no

我该怎么做?

2 个答案:

答案 0 :(得分:0)

取决于您的表格,它将类似于以下内容

System.Xml.Linq

答案 1 :(得分:0)

你可以使用它。

SELECT 
    SUM(col1) col1, 
    SUM(col2) col2,
    SUM(col3) col3,
    year,
    class,
    (case when type = 1 then 'yes' else 'no' end)  as new 
FROM MyTable
GROUP BY year, class, (case when type = 1 then 'yes' else 'no' end) 

结果:

col1        col2        col3        year        class new
----------- ----------- ----------- ----------- ----- ----
10          10          10          2017        A     no
1           3           4           2017        A     yes
2           2           2           2017        B     no
1           1           1           2017        B     yes
相关问题