2017-01-12 74 views
1

比方說,我有一個數據集如下一個子集:SQL Case語句的邏輯是現有的邏輯

+----------+-------+----------+ 
| Customer | Price | Order ID | 
+----------+-------+----------+ 
| john  | 4  | 1  | 
| john  | 7  | 2  | 
| mike  | 12 | 3  | 
| mike  | 3  | 4  | 
| stacy | 3  | 5  | 
| stacy | 8  | 6  | 
+----------+-------+----------+ 

我想創建一個報告,讓2組,其價格的總和,一個GROUP A [john + mike + stacy],另一個是B組[約翰+麥克]。
當我嘗試在SQL語句中編寫案例邏輯時發生問題。
由於組B是基團A的一個子集,它之前的情況下語句退出達到用於GROUP B. 邏輯說我使用此代碼:

with grouped_prices as (
select 
case when customer in ('john', 'mike', 'stacy') then 'GROUP A' 
when customer in ('john', 'mike') then 'GROUP B' 
else null end as customer_groups 
, price 
from mytable 
) 
select 
customer_groups 
, sum(price) as total 
from grouped_prices 
group by customer_groups 

這產生的結果

+-----------------+-------+ 
| customer_groups | total | 
+-----------------+-------+ 
| GROUP A   | 37 | 
+-----------------+-------+ 

但我想要的是

+-----------------+-------+ 
| customer_groups | total | 
+-----------------+-------+ 
| GROUP A   | 37 | 
+-----------------+-------+ 
| GROUP B   | 26 | 
+-----------------+-------+ 

我可以實現此解決方案使用UNION ALL語句,但我必須掃描表兩次,然後這是不高效的。有沒有比UNION ALL更聰明的解決方案,我沒有看到?

+0

爲什麼MySQL的標籤? – Strawberry

+0

只是爲了防止人們在尋找特定語言,但我認爲case語句以我所知道的所有方言進行操作(redshift,oracle,mysql,transact ...) – barker

+1

這就是所謂的標籤垃圾郵件。不要這樣做。 – shmosel

回答

1

更新回答

你可以加入到被動態創建如下派生表:

select sum(cp.Price) as Total, t.Group 
from CustomerPrices cp 
join 
    (select 'Joe' as Customer, 'Group A' as Group 
    union all 
    select 'Sam' as Customer, 'Group A' as Group 
    union all 
    select 'John' as Customer, 'Group A' as Group 
    union all 
    select 'Joe' as Customer, 'Group B' as Group 
    union all 
    select 'John' as Customer, 'Group B' as Group) as t on t.Customer = cp.Customer 
group by t.Group 
+0

感謝達納,這是我目前使用的解決方案,但聯合聲明將執行表掃描2次。你知道一種方法來實現這個邏輯與1表掃描? – barker

+0

@barker - 如果您在不同的表中定義了組成員身份,那麼您可以在單個查詢中運行一些事情(我在答案中添加了一個示例)。另外,您可以考慮在「客戶」列中添加一個索引。 – dana

+0

感謝dana的幫助,我們得出了同樣的初步結論。我張貼的原因是因爲我想看看,也許我可以創建一個嵌套的case語句?或任何方式來解決這個在1表掃描:)這是棘手的,這些組不存在於任何表。 – barker