簡體   English   中英

SQL 服務器中 2 個變量的不同計數

[英]Distinct count of 2 variables in SQL Server

我的表有列idstatus ( failed , success ) 和status_id 在保存成功響應之前,失敗條目是多余的。 如何獲取不同的成功和失敗計數失敗嘗試只計算一次?

我試過的查詢:

select 
    sum(case when status_id in (1,2,3,4) then 1 else 0 end) as success, 
    sum(case when status_id in (5,6,7,8) then 1 else 0 end) as failed
from test

此查詢有效,但失敗的嘗試計數兩次

ID status_id 地位
123 5 失敗的
123 1 成功
123 7 失敗的
123 5 失敗的

所需 output 成功 - 1 失敗 - 2

要僅計算每個成功/失敗一次,請在聚合之前在派生表中執行select distinct

select 
    sum(case when status_id in (1,2,3,4) then 1 else 0 end) as success, 
    sum(case when status_id in (5,6,7,8) then 1 else 0 end) as failed
from (select distinct status_id from test) dt

計算唯一的 status_id 可能會起作用。

select 
 COUNT(DISTINCT case when status_id in (1,2,3,4) then status_id end) as success, 
 COUNT(DISTINCT case when status_id in (5,6,7,8) then status_id end) as failed
from test

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM