我需要一个小的SQL查询帮助。 请考虑下表:
TicketNo | Rules | Audit Result
---------------------------------
PR123 | some random strings | Audited
PR123 | some random strings | Not Audited
PR123 | some random strings | Audited
PR123 | some random strings | Audited
PR123 | some random strings | Not Audited
PR123 | some random strings | Not Audited
PR123 | some random strings | Audited
PR999 | some random strings | Audited
PR999 | some random strings | Audited
PR999 | some random strings | Audited
PR999 | some random strings | Audited
PR999 | some random strings | Audited
PR111 | some random strings | Not Audited
PR111 | some random strings | Not Audited
PR111 | some random strings | Not Audited
PR111 | some random strings | Not Audited
我需要以下结果:
Ticket | Count of Audited Rules | Count of NOT-Audited Rules
------------------------------------------------------------
PR123 | 4 | 3
PR999 | 5 | 0
PR111 | 0 | 4
我试过了:
Select T1.TicketNo,T1.Audited_Count,T2.NonAudited_Count
FROM
(
Select [TicketNo], COUNT([TicketNo]) AS Audited_Count
from [Resolved Results$] where [Audit Result] = 'Audited'
group by TicketNo
) T1
inner JOIN
(
Select [TicketNo], COUNT([TicketNo]) AS NonAudited_Count
from [Resolved Results$] where [Audit Result] <> 'Audited'
group by TicketNo
) T2
on T1.[TicketNo] = T2.[TicketNo]
但是上述命令不适用于那些拥有最低审计规则或仅有未经审计的规则的票证,但仅对具有这两种规则的票证有效。
有人可以帮我解决问题吗?
请注意:只有内部联接可以与OleDB一起使用,因此请避免使用除内部联接之外的任何内容。 非常感谢
编辑:戈登的第一个答案应该是理想的工作,但不幸的是,OLED的OLEDB驱动程序不支持它。但是,戈登建议使用iff(..)工作。我正在使用的最终查询是:
select [TicketNo],
sum(iif([Audit Result] = "AUDITED", 1, 0)) as Audited,
sum(iif([Audit Result] = "NOT AUDITED", 1, 0)) as NotAudited
from [Resolved Results$]
group by [TicketNo];
谢谢戈登!
答案 0 :(得分:6)
您需要条件求和,您可以通过在case
中添加sum()
语句来执行此操作:
select ticket,
sum(case when AuditResult = 'Audited' then 1 else 0 end) as Audited,
sum(case when AuditResult = 'Not Audited' then 1 else 0 end) as NotAudited
from t
group by ticket;
这假设AuditResult是一个单独的列。如果是SomeStrings
的最终评论,那么查询将如下所示:
select ticket,
sum(case when SomeStrings like '%Audited' and SomeStrings not like '%Not Audited' then 1
else 0
end) as Audited,
sum(case when SomeStrings like '%Not Audited' then 1
else 0
end) as NotAudited
from t
group by ticket;