我有一张数据表,其中记录了过去几周的通过和失败。
我想计算每周的尝试次数以及通过和失败的次数,然后取这些通过和失败的总和作为检查。
SELECT week,
COUNT (Week) as weekcount,
sum(case when result = 'pass' then 1 else 0 end) as 'passcount' ,
sum(case when result = 'fail' then 1 else 0 end) as 'failcount',
sum(case when result = 'pass' then 1 else 0 end) +
sum(case when result = 'fail' then 1 else 0 end) as 'sum'
FROM table1
group by week
order by week
上面的代码段可以满足我的要求,但是我一直在阅读有关CTE的信息,以代替在查询中进行重复操作。
我希望能够在查询中使用别名“ passcount”和“ failcount”,而无需将它们作为列添加到表中。我尝试先在下面设置CTE。
with sums as
(
select result,
sum(case when result = 'pass' then 1 else 0 end) as 'passcount' ,
sum(case when result = 'fail' then 1 else 0 end) as 'failcount',
from table1
)
以上报告了右括号附近的语法错误,但我不明白为什么。
任何人都可以阐明这种方法或更好的方法吗?
答案 0 :(得分:1)
在SQL Server中,我认为横向联接(即^compose
)比子查询和CTE更清洁。在您的情况下,您可以在聚合之前 生成标志,因此如下所示:
cross apply
答案 1 :(得分:1)
您仅需再进行一次选择就可以了
using namespace std::chrono;
system_clock::time_point tp{system_clock::duration{i}};
答案 2 :(得分:1)
您实际上不需要同时编写两个CASE
表达式,而只需使用IN
:
SELECT Week,
COUNT(Week) AS weekcount,
COUNT(CASE Result WHEN 'pass' THEN 1 END) AS PassCount,
COUNT(CASE Result WHEN 'fail' THEN 1 END) AS FailCount,
COUNT(CASE WHEN Result IN ('pass','fail') THEN 1 END) AS PassFailCount
FROM Table1
GROUP BY Week
ORDER BY Week;
是的,这没有告诉您如何使用CTE,但是,与重复两个CASE
表达式相比,逻辑是“更干净”(更简洁)。
答案 3 :(得分:1)
我不确定您为什么要考虑CTE,您可以将它设置为一组:
SELECT
[Week],
COUNT([Week]) AS weekcount
, SUM(CASE WHEN result = 'pass' THEN 1 ELSE 0 END) AS passcount
, SUM(CASE WHEN result = 'fail' THEN 1 ELSE 0 END) AS failcount
, COUNT(*) AS TotalSum
FROM table1
GROUP BY [Week]
在SQL Server中,您不能引用同一SELECT中的别名,例如密码,周数等。这样,您就需要一种变通方法,例如使用子查询,CTE,JOIN,CROSS APPLY或任何其他可用于此目的的方法。
以下是一些常用方法:
使用子查询:
SELECT
[Week]
, SUM(weekcount) weekcount
, SUM(passcount) passcount
, SUM(failcount) failcount
, SUM(passcount + failcount) AS TotalSum
FROM (
SELECT
[Week],
COUNT([Week]) AS weekcount
, SUM(CASE WHEN result = 'pass' THEN 1 ELSE 0 END) AS passcount
, SUM(CASE WHEN result = 'fail' THEN 1 ELSE 0 END) AS failcount
FROM table1
GROUP BY [Week]
) D
GROUP BY
[Week]
使用CTE 方法:
;WITH CTE AS (
SELECT
[Week],
COUNT([Week]) AS weekcount
, SUM(CASE WHEN result = 'pass' THEN 1 ELSE 0 END) AS passcount
, SUM(CASE WHEN result = 'fail' THEN 1 ELSE 0 END) AS failcount
FROM table1
GROUP BY [Week]
)
SELECT
[Week]
, SUM(weekcount) weekcount
, SUM(passcount) passcount
, SUM(failcount) failcount
, SUM(passcount + failcount) AS TotalSum
FROM CTE
GROUP BY
[Week]
使用交叉应用方法: 请参阅@Gordon Linoff答案(基本而直接)。
这些是您可以在案例中使用的最简单的方法。您也可以在案例中使用PIVOT,但是为了简单起见,我没有提到它。