我有一个有效的查询,但似乎可以/应该以更优雅的方式重写。问题是,由于HAVING
声明,我还没有办法做到这一点。
我只想看一下顾客购买的3家商店中的哪一家,并为他们指定一家主店。'
我结束了UNION
7个不同的案件......它有点荒谬。
在我完美的世界中,我能够以某种方式使用HAVING . . OR HAVING . .
,但这似乎与MySQL的哲学不符。
SELECT Cust_ID, 'Main_store_1' AS Main_Store, sum(StoreName = 'Store_1') as num_Store_1, sum(StoreName = 'Store_2') as num_Store_2, sum(StoreName = 'Store_3') as num_Store_3
FROM shopping_table
WHERE Cust_ID in (<some list of Cust_IDs>)
AND StoreName in ('Store_1', 'Store_2', 'Store_3')
GROUP BY Cust_ID
HAVING num_Store_1 > 1 and num_Store_2 = 0 and Store_3 = 0
UNION
SELECT Cust_ID, 'Main_store_2' AS Main_Store, sum(StoreName = 'Store_1') as num_Store_1, sum(StoreName = 'Store_2') as num_Store_2, sum(StoreName = 'Store_3') as num_Store_3
FROM shopping_table
WHERE Cust_ID in (<some list of Cust_IDs>)
AND StoreName in ('Store_1', 'Store_2', 'Store_3')
GROUP BY Cust_ID
HAVING num_Store_1 = 0 and num_Store_2 > 0 and Store_3 = 0
和建议/哲学意见将不胜感激。感谢。
答案 0 :(得分:1)
没有完全重写(我很确定有更好的方法,但它可能相当冗长),这种修改应该有效:
SELECT q.*
, CASE
WHEN (num_Store_1 > 1 and num_Store_2 = 0 and Store_3 = 0)
THEN 'Main_store_1'
WHEN (num_Store_1 = 0 and num_Store_2 > 0 and Store_3 = 0)
THEN 'Main_store_2'
WHEN [more conditions]
THEN [another string]
ELSE 'No Main'
END AS Main_Store
FROM (
SELECT Cust_ID
, sum(StoreName = 'Store_1') as num_Store_1
, sum(StoreName = 'Store_2') as num_Store_2
, sum(StoreName = 'Store_3') as num_Store_3
FROM shopping_table
WHERE Cust_ID in (<some list of Cust_IDs>)
AND StoreName in ('Store_1', 'Store_2', 'Store_3')
GROUP BY Cust_ID
) AS q
;
答案 1 :(得分:0)
试试这个:
...HAVING (num_Store_1 > 1 and num_Store_2 = 0 and Store_3 = 0) OR (num_Store_1 = 0 and num_Store_2 > 0 and Store_3 = 0)
答案 2 :(得分:0)
你真的只有兴趣列出在一家商店独家购物的顾客,然后可以使用:
SELECT Cust_ID,
Max(StoreName) as Main_Store,
Sum(StoreName = 'Store_1') as num_Store_1,
Sum(StoreName = 'Store_2') as num_Store_2,
Sum(StoreName = 'Store_3') as num_Store_3
FROM shopping_table
WHERE Cust_ID in (<some list of Cust_IDs>)
AND StoreName in ('Store_1', 'Store_2', 'Store_3')
GROUP BY Cust_ID
HAVING Count(DISTINCT StoreName) = 1
或者,如果您还要列出其他客户,并选择他们访问过的最重要商店作为他们的主要商店,那么请使用CASE
每个商店WHEN
,降序优先顺序:
SELECT Cust_ID,
CASE
WHEN Sum(StoreName = 'Store_1') > 0 THEN 'Store_1'
WHEN Sum(StoreName = 'Store_2') > 0 THEN 'Store_2'
WHEN Sum(StoreName = 'Store_3') > 0 THEN 'Store_3'
END as Main_Store,
Sum(StoreName = 'Store_1') as num_Store_1,
Sum(StoreName = 'Store_2') as num_Store_2,
Sum(StoreName = 'Store_3') as num_Store_3
FROM shopping_table
WHERE Cust_ID in (<some list of Cust_IDs>)
AND StoreName in ('Store_1', 'Store_2', 'Store_3')
GROUP BY Cust_ID