我似乎无法弄清楚如何为我的特定问题设置逻辑。我试图计算单词" Service"的次数。出现但仅在RECORD_CODE为INCIDENT时出现。当RECORD是INCIDENT-UPDATE时,它通常已经在其他地方作为INCIDENT,因此我将它们排除在外以防止重复我的数据。
但是,有少数情况下SUBMIT_METHOD是" WEB"并且唯一的记录是INCIDENT_UPDATE,我无法弄清楚如何仅查看RECORD =' INCIDENT'除非特定记录的SUBMIT_METHOD为" WEB"并且没有该报告的记录#带有意外记录。这可能是一个简单的问题,我只是在思考它,但我想不出怎么做。任何帮助都会非常感激!
我的查询:
SELECT column2, count(*) as 'COUNT'
from Service.Table
where date between '1/1/17' and '1/31/17'
and column1 = 'Issue'
and RECORD = 'INCIDENT'
group by column2
数据样本:
REPORT # RECORD SUBMIT_METHOD SUBMIT_DATE COLUMN2
1234 Incident Web 1/1/2017 Service
1234 Incident-Update Web 1/1/2017 Service
1235 Incident Phone 1/15/2017 Other
1235 Incident-Update Phone 1/15/2017 Other
1236 Incident-Update Web 1/18/2017 Service
这种情况下的预期输出是:
COLUMN2 COUNT
Service 3
如果我能提供任何其他信息,请告诉我!
答案 0 :(得分:0)
您正在寻找group by
喜欢的
select column2, count(*)
from tbl1
where SUBMIT_METHOD = 'Web'
group by column2;
答案 1 :(得分:0)
您可以使用not exists
子查询来确保没有其他行具有相同的Report#和记录类型INCIDENT:
select *
from Service.Table t1
where date between '1/1/17' and '1/31/17' and
column1 = 'Issue' and
(
record = 'Incident' or
(
record = 'Incident-Update' and
submit_method = 'Web' and
not exist
(
select *
from Service.Table t2
where t2.record = 'INCIDENT'
and t2.[Report #] = t1.[Report #]
)
)
)
答案 2 :(得分:0)
;With cte(REPORT#,RECORD ,SUBMIT_METHOD,SUBMIT_DATE,COLUMN2)
AS
(
SELECT 1234,'Incident' ,'Web' , '1/1/2017' ,'Service' Union all
SELECT 1234,'Incident-Update' ,'Web' , '1/1/2017' ,'Service' Union all
SELECT 1235,'Incident' ,'Phone', '1/15/2017', 'Other' Union all
SELECT 1235,'Incident-Update' ,'Phone', '1/15/2017', 'Other' Union all
SELECT 1236,'Incident-Update' ,'Web' , '1/18/2017', 'Service'
)
SELECT COLUMN2
,CountCOLUMN2
FROM (
SELECT *
,COUNT(COLUMN2) OVER (
PARTITION BY COLUMN2 ORDER BY COLUMN2
) CountCOLUMN2
,ROW_NUMBER() OVER (
PARTITION BY COLUMN2 ORDER BY COLUMN2
) Seq
FROM cte
) Dt
WHERE SUBMIT_DATE BETWEEN '1/1/17'
AND '1/31/17'
AND RECORD = 'INCIDENT'
ORDER BY 1 DESC
输出
COLUMN2 CountCOLUMN2
--------------------
Service 3
Other 2