2015-10-13 53 views
1

我有一個表有兩列,CustomerId & Status(A,B,C)。SQL查詢基於過濾狀態獲得計數

客戶可以在不同的行中擁有多個狀態。

我需要基於以下規則不同的狀態計數:

  1. 如果客戶的狀態是& B,他應該在狀態A.計入
  2. 如果狀態是既乙& C,它應該在狀態B.算作
  3. 如果狀態是三個點,它將在狀態A.

我需要的是有狀態的表d數。

可以請別人幫忙嗎?

我知道有人會問我先寫我的查詢,但我無法理解如何在查詢中實現這個邏輯。

回答

2

你可以用這種不同的變化發揮:

select customerId, 
     case when HasA+HasB+HasC = 3 then 'A' 
      when HasA+HasB = 2 then 'A' 
      when HasB+HasC = 2 then 'B' 
      when HasA+HasC = 2 then 'A' 
      when HasA is null and HasB is null and HasC is not null then 'C' 
      when HasB is null and HasC is null and HasA is not null then 'A' 
      when HasC is null and HasA is null and HasB is not null then 'B' 
     end as overallStatus 
from 
    (
    select customerId, 
      max(case when Status = 'A' then 1 end) HasA, 
      max(case when Status = 'B' then 1 end) HasB, 
      max(case when Status = 'C' then 1 end) HasC 
    from tableName 
    group by customerId 
    ) as t; 
+0

是的,它給不同的是所期望的結果對於單個狀態返回null。我仍然試圖弄清楚它的正確性。如果你也可以包括它,那可能是一個被接受的答案。 – smokingkills

0

我喜歡用十字申請該類型的查詢,因爲它允許使用了該組的計算狀態BY子句。

這裏是我的解決方案與一些示例數據。

Declare @Table Table (Customerid int, Stat varchar(1)) 

INSERT INTO @Table (Customerid, Stat) 
VALUES 
(1, 'a'), 
(1 , 'b'), 
(2, 'b'), 
(2 , 'c'), 
(3, 'a'), 
(3 , 'b'), 
(3, 'c') 



SELECT 
ca.StatusGroup 
, COUNT(DISTINCT Customerid) as Total 
FROM 
@Table t 
CROSS APPLY 
    (VALUES 
     (
     CASE WHEN 
      EXISTS 
      (SELECT 1 FROM @Table x where x.Customerid = t.CustomerID and x.Stat = 'a') 
      AND EXISTS 
      (SELECT 1 FROM @Table x where x.Customerid = t.CustomerID and x.Stat = 'b') 
      THEN 'A' 
     WHEN 
      EXISTS 
      (SELECT 1 FROM @Table x where x.Customerid = t.CustomerID and x.Stat = 'b') 
      AND EXISTS 
      (SELECT 1 FROM @Table x where x.Customerid = t.CustomerID and x.Stat = 'c') 
      THEN 'B' 
      ELSE t.stat 
     END 
     ) 
    ) ca (StatusGroup) 

GROUP BY ca.StatusGroup 

我編輯這與客戶打交道誰只能有一個狀態......在這種情況下,它會返回A,B或C取決於客戶狀態

+0

感謝DaveFoyf,但我想第一個解決方案更具可讀性。除此之外,我認爲在使用交叉連接時,執行時間會更多。 – smokingkills