0
如何按原始結果的結果進行分組並返回同一選擇查詢?如何按原始結果的結果進行分組並返回同一選擇查詢?
我有一個表#t
與Bill Id和錯誤的工作流程週期。一個賬單ID可能已經經歷了多次相同的錯誤類型或不同的錯誤類型。
我想爲每個帳單id挑選不同的錯誤類型並獲取按錯誤計數組。
基於不同的錯誤,錯誤計數,我需要在同一個表中獲取錯誤類型計數和錯誤類型。
我不知道該怎麼做。我在本文中保留了示例查詢和預期結果。
create table #t
(
BillId int,
StepName varchar(100),
StepExec varchar(100),
StepExecResult varchar(100),
Created_date datetime
)
insert into #t
values
(1, 'Initiated', 'Taken Place','Pass', getdate()-10),
(1, 'POS', 'Deadlock Error','Error', getdate()-9),
(1, 'POS', 'Processed','Pass', getdate()-9),
(1, 'Merchandise', 'Taken Place','Pass', getdate()-8),
(1, 'verification', 'Webservice call error','Error', getdate()-7),
(1, 'verification', 'Webservice call error','Error', getdate()-6),
(1, 'verification', 'Webservice call','Pass', getdate()-5),
(1, 'verification', 'Webservice Response','Error', getdate()-5),
(1, 'verification', 'Webservice Response','Pass', getdate()-5),
(1, 'verification', 'Timeout Error','Error', getdate()-5),
(1, 'verification', 'Timeout Error','Error', getdate()-5),
(1, 'verification', 'Timeout Error','Error', getdate()-5),
(1, 'verification', '','Pass', getdate()-5),
(1, 'Payment', 'calculationError','Error', getdate()-4),
(1, 'Payment', 'calculationProcessed','Pass', getdate()-3),
(1, 'Completed', 'Archived','Pass', getdate()-1),
(2, 'Initiated', 'Taken Place','Pass', getdate()-10),
(2, 'POS', 'Deadlock Error','Error', getdate()-9),
(2, 'POS', 'Processed','Pass', getdate()-9),
(2, 'Merchandise', 'Taken Place','Pass', getdate()-8),
(2, 'verification', 'Webservice call error','Error', getdate()-7),
(2, 'verification', 'Webservice call error','Error', getdate()-6),
(2, 'verification', 'Webservice call','Pass', getdate()-5),
(2, 'verification', 'Webservice Response','Error', getdate()-5),
(2, 'verification', 'Webservice Response','Pass', getdate()-5),
(2, 'verification', '','Pass', getdate()-5),
(2, 'Payment', 'calculationProcessed','Pass', getdate()-3),
(2, 'Completed', 'Archived','Pass', getdate()-1)
select *
from #t
order by Created_date desc
select *
from #t
where StepExecResult = 'Error'
;With cte as
(
select
*,
row_number() over (partition by Billid,StepExec order by StepExecResult) as rownum
from
#t
where
StepExecResult = 'Error'
)
select *
from cte
where rownum = 1
select
stepname, count(*) as ErrorCount
from
#t
where
StepExecResult = 'Error'
group by
stepname
預計輸出
StepName TotalStepError ErrorType ErrorTypeCount
--------------------------------------------------------------
Payment 1 calculationError 1
POS 2 Deadlock Error 2
verification 5 Timeout Error 1
verification 5 Webservice Response 2
verification 5 Webservice call error 2
謝謝傑米。這非常有幫助..! – goofyui