比方說,我有一個數據集如下一個子集: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更聰明的解決方案,我沒有看到?
爲什麼MySQL的標籤? – Strawberry
只是爲了防止人們在尋找特定語言,但我認爲case語句以我所知道的所有方言進行操作(redshift,oracle,mysql,transact ...) – barker
這就是所謂的標籤垃圾郵件。不要這樣做。 – shmosel