我有一个看起来像这样的SQL表:
表格定义:
CREATE TABLE TestSessions(Id INTEGER IDENTITY(1,1)PRIMARY KEY not null,TestUser varchar(50)not null,Department varchar(50)not null,Project varchar(50)not null,TestDateTime varchar(50)not not null,Score varchar(50)not null,Pass varchar(50)not null);
我想通过TestUser对表进行分组,并为每个TestUser计算每个Pass(Passes and Fails)值,使其看起来像:
SQL命令:“SELECT TestUser,SUM(CASE WHEN [Score] ='Pass'THEN 1 ELSE 0 END)[Pass],SUM(CASE WHEN [Score] ='Fail'THEN 1 ELSE 0 END)[Fail ] FROM TestSessions GROUP BY TestUser“
返回:
我该如何解决这个问题?
然后我想计算通行证和失败之间的比率。
这可能在一个声明中吗?
答案 0 :(得分:5)
您需要一个简单的聚合和CASE
表达式:
SELECT Color,
SUM(CASE WHEN [BOOL] = 'TRUE' THEN 1 ELSE 0 END) [True],
SUM(CASE WHEN [BOOL] = 'FALSE' THEN 1 ELSE 0 END) [False]
FROM dbo.YourTable
GROUP BY Color;
这假设BOOL
的数据类型是varchar,如果它有点,那么你需要这样做:
SELECT Color,
SUM(CASE WHEN [BOOL] = 1 THEN 1 ELSE 0 END) [True],
SUM(CASE WHEN [BOOL] = 0 THEN 1 ELSE 0 END) [False]
FROM dbo.YourTable
GROUP BY Color;
答案 1 :(得分:1)
首先,你的CASE应该检查[Pass]列而不是[Score],因为[Score]从不包含“Pass”或“Fail”。其次,你可以尝试在它周围写一个cte,就像以下内容:
WITH cte AS (
SELECT TestUser
,Department
,CASE WHEN [Pass] = 'Pass' THEN 1 ELSE 0 END [Passed]
,CASE WHEN[Pass] = 'Fail' THEN 1 ELSE 0 END [Failed]
FROM TestSessions
)
SELECT TestUser
,Department
,sum([Passed]) [Pass]
,sum([Failed]) [Fail]
FROM cte
GROUP BY TestUser, Department