2

我需要一个小型 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 只能使用内部联接,因此请避免使用内部联接以外的任何东西。非常感谢

编辑:戈登的第一个答案应该可以正常工作,但不幸的是 Excel 的 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];

谢谢戈登!

4

1 回答 1

6

您需要条件求和,您可以通过在 a 中放置一条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;
于 2013-09-02T13:26:31.737 回答