在ms-sql中我使用聚合组来按用户过滤结果,我还想使用大小写来过滤未包含在聚合中的行,这样所有用户结果都在1行上。我不确定这是可能的。
以下是下面的查询,将结果分成两行。
select case when col_A='1' then sum(col b) End as Sum1_results,
case when col_A='2' then sum(col_b) End as Sum2_Results, Username from tbl1
group by Username, col_A
结果的例子是。
Sum1_results | Sum2_results | Username
5499 null John
null 3400 John
理想情况下,如果可能的话,我希望将这些结果合并为每个用户名的一行。 任何帮助将不胜感激
答案 0 :(得分:2)
您可以使用:
select Username ,
SUM(case when col_A='1' then col_b End) as Sum1_results,
SUM(case when col_A='2' then col_b End) as Sum2_Results,
from tbl1
group by Username
答案 1 :(得分:1)
下面的查询可以完成这项工作
Create table #tmp (col_A CHAR(1),col_b int,Username VARCHAR(10))
INSERT INTO #tmp VALUES('1',5000,'John')
INSERT INTO #tmp VALUES('2',400,'John')
INSERT INTO #tmp VALUES('1',499,'John')
INSERT INTO #tmp VALUES('2',3000,'John')
SELECT * FROM #tmp
select SUM(case when col_A='1' then col_b End) as Sum1_results,
SUM(case when col_A='2' then col_b End) as Sum2_Results,Username
from #tmp
group by col_A,UserName
DROP TABLE #tmp
答案 2 :(得分:0)
每个用户名的结果合并为一行。
创建表#tmp(col_A CHAR(1),col_b int,Username VARCHAR(10))
INSERT INTO #tmp VALUES('1',5000,'John')
INSERT INTO #tmp VALUES('2',400,'John')
INSERT INTO #tmp VALUES('1',499,'John')
INSERT INTO #tmp VALUES('2',3000,'John')
SELECT * FROM #tmp
select SUM(case when col_A='1' then col_b End) as Sum1_results,
SUM(case when col_A='2' then col_b End) as Sum2_Results,Username
from #tmp
group by UserName
DROP TABLE #tmp