我通过使用我的商店程序获得以下结果。在消除空值后,如何只获得一行结果。 ?
`cte_Sum
as
(
Select sum(NumberOfCode) as NumberOfCode, CodeName, Code, Quarters, Q1s, Q2s, Q3s, Q4s
from cte_totals
group by CodeName, Code, Quarters, Q1s, Q2s, Q3s, Q4s
)
Select
CodeName,Code,
Case When Quarters = 'Q1' Then NumberOfCode End as Q1_Number,
Case When Quarters = 'Q1' Then Q1s End as Q1_Date,
Case When Quarters = 'Q2' Then NumberOfCode End as Q2_Number,
Case When Quarters = 'Q2' Then Q2s End as Q2_Date,
Case When Quarters = 'Q3' Then NumberOfCode End as Q3_Number,
Case When Quarters = 'Q3' Then Q3s End as Q3_Date,
Case When Quarters = 'Q4' Then NumberOfCode End as Q4_Number,
Case When Quarters = 'Q4' Then Q4s End as Q4_Date
from cte_Sum`
答案 0 :(得分:0)
使用聚合:
Select CodeName, Code,
sum(Case When Quarters = 'Q1' Then NumberOfCode End) as Q1_Number,
max(Case When Quarters = 'Q1' Then Q1s End) as Q1_Date,
sum(Case When Quarters = 'Q2' Then NumberOfCode End) as Q2_Number,
max(Case When Quarters = 'Q2' Then Q2s End) as Q2_Date,
sum(Case When Quarters = 'Q3' Then NumberOfCode End) as Q3_Number,
max(Case When Quarters = 'Q3' Then Q3s End) as Q3_Date,
sum(Case When Quarters = 'Q4' Then NumberOfCode End) as Q4_Number,
max(Case When Quarters = 'Q4' Then Q4s End) as Q4_Date
from cte_Sum
group by CodeName, Code;
我不认为CTE会有所帮助。你也可以这样做:
Select CodeName, Code,
sum(Case When Quarters = 'Q1' Then NumberOfCode else 0 End) as Q1_Number,
max(Case When Quarters = 'Q1' Then Q1s End) as Q1_Date,
sum(Case When Quarters = 'Q2' Then NumberOfCode else 0 End) as Q2_Number,
max(Case When Quarters = 'Q2' Then Q2s End) as Q2_Date,
sum(Case When Quarters = 'Q3' Then NumberOfCode else 0 End) as Q3_Number,
max(Case When Quarters = 'Q3' Then Q3s End) as Q3_Date,
sum(Case When Quarters = 'Q4' Then NumberOfCode else 0 End) as Q4_Number,
max(Case When Quarters = 'Q4' Then Q4s End) as Q4_Date
from cte_totals
group by CodeName, Code;
您也可以简化cte_totals
,但您的问题并未显示该代码。
答案 1 :(得分:0)
对于那些Q2-Q4列不为NULL的行,我会自行离开。
select t1.CodeName ,t1.Code ,
Q2.Q2_NUmber, Q2.Q2_DAte,
Q3.Q3_NUmber, Q3.Q3_DAte,
Q4.Q4_NUmber, Q4.Q4_DAte
from table t1
left join (select Code, Q2_Number, Q2_Date where Q2_Number is not NULL) Q2 on t1.Code = Q2.Code
left join (select Code, Q3_Number, Q3_Date where Q3_Number is not NULL) Q3 on t1.Code = Q3.Code
left join (select Code, Q4_Number, Q4_Date where Q4_Number is not NULL) Q4 on t1.Code = Q4.Code