簡體   English   中英

根據 ID 數量選擇

[英]Select based on count of IDs

我有一個通過selectcasegroup by語句獲得的客戶列表。 我得到了正確的值,但我的問題如下:

我的桌子

 ID Name Contract
 1  ABC  Contract
 2  DEF  No Contract
 2  DEF  Contract
 3  GHI  No Contract

一些客戶可以是合同的一部分,而不是客戶2一部分。 我需要從中選擇一個給我:

 ID Name Contract
 1  ABC  Contract
 2  DEF  Mixed
 3  GHI  No Contract

如果客戶id只出現一次,我需要按原樣使用Contract ,否則我希望客戶使用Mixed for Contract一詞一次

這是我到目前為止:

with T as(
  select [DEBTORID]
  , [DEBTOR]
  , case 
    when [CONTRACTTYPE]='KAM' then 'Contract' 
    when [CONTRACTTYPE]='SME' then 'Contract' 
    when [CONTRACTTYPE]='CCS' then 'Contract' 
    else 'Deemed' 
    end as 'Contract'
  FROM [FinancialReporting].[dbo].[LiveGasMeters]
  group by [DEBTORID],[DEBTOR],[CONTRACTTYPE]
  )
  select T.[DEBTORID]
  , T.DEBTOR
  , T.[Contract]
  from T
  group by [DEBTORID],DEBTOR,[Contract]

您可以group by id, name進行group by id, name進行聚合並使用CASE表達式:

select id, name,
  case count(distinct contract)
    when 1 then max(contract)
    else 'Mixed'
  end Contract
from tablename
group by id, name

請參閱演示
結果:

> id | name | Contract   
> -: | :--- | :----------
>  1 | ABC  | Contract   
>  2 | DEF  | Mixed      
>  3 | GHI  | No Contract

我會這樣寫:

select id, name,
       (case when min(contract) = max(contract) then min(contract)
             else 'Mixed'
        end) as contract
from t
group by id, name;

暫無
暫無

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

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