Sql 对列名来自另一列的列求和';s值
我想对其中一列求和,该列名称来自另一列值(第2列) 已经尝试过的案例功能似乎没有希望Sql 对列名来自另一列的列求和';s值,sql,oracle,Sql,Oracle,我想对其中一列求和,该列名称来自另一列值(第2列) 已经尝试过的案例功能似乎没有希望 select col.1, col.2, sum(case when col.2='Q1' then 'Q1', when col.2='Q2' then 'Q2' end as Total) from tabl group by col.1, col.2 Col.1 Col.2 Q1 a Q1 3 c Q1 2 如果我理解清楚,您可能需要: select Col1, Col2,
select col.1, col.2, sum(case when col.2='Q1' then 'Q1',
when col.2='Q2' then 'Q2' end as Total)
from tabl
group by col.1, col.2
Col.1 Col.2 Q1
a Q1 3
c Q1 2
如果我理解清楚,您可能需要:
select Col1, Col2,
sum(
case
when Col2='Q1' then Q1
when Col2='Q2' then Q2
else 0
end
) as Total
from yourTable
group by Col1, Col2
例如,使用示例数据:
with yourTable(Col1, Col2, Q1, Q2, Q3) as (
select 'a', 'Q1', 1, 1, 4 from dual union all
select 'a', 'Q1', 2, 1, 1 from dual union all
select 'c', 'Q1', 2, 1, 2 from dual
)
select Col1, Col2,
sum(
case
when Col2='Q1' then Q1
when Col2='Q2' then Q2
else 0
end
) as Total
from yourTable
group by Col1, Col2
给出:
COL1 COL2 TOTAL
---- ---- ----------
a Q1 3
c Q1 2
只需将
'Q1'
替换为Q1
,将'Q2'
替换为Q2
:
select col1
, col2
, sum(case
when col2 = 'Q1' then Q1,
when col2 = 'Q2' then Q2
end) as Total
from tabl
group by col1, col2
它起作用了!非常感谢。但这里有另一个问题。当我按Col1,Col2分组并按Col1,Col2排序时,Col1的空值到达最后一行。我想把它放在第一排。我尝试使用“Order by Col1 NULLS FIRST,Col2”,但NULL值位于底部。为什么?当我按Col1,Col2分组并按Col1,Col2排序时,Col1的空值出现在最后一行。我想把它放在第一排。我尝试使用“Order by Col1 NULLS FIRST,Col2”,但NULL值位于底部。为什么?
select col1
, col2
, sum(case
when col2 = 'Q1' then Q1,
when col2 = 'Q2' then Q2
end) as Total
from tabl
group by col1, col2