将GROUP BY / CASE与WHEN或IF一起使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将GROUP BY / CASE与WHEN或IF一起使用相关的知识,希望对你有一定的参考价值。

注意:下面编辑的查询。

我希望根据两个标准对数据集进行分段:

  1. 如果客户在特定餐厅的价格高于或低于4 txns
  2. 如果客户在该数据集中的所有其他餐馆中具有多于或少于24个txns。

我正在使用GROUP BY,CASE和WHEN或IF的组合。我不确定哪种方法最好,如果有的话?

SELECT 
COUNT(Customer) AS number_of_customers, 
AVG (CASE WHEN ItemPrice LIKE '-%' THEN NULL
WHEN ItemPrice LIKE '0%' THEN NULL
ELSE CAST (ItemPrice AS FLOAT) END) AS avg_item_price, 
COUNT(DISTINCT(ReceiptIDDesc)) AS number_of_orders, 
SUM(CAST(ItemPrice AS FLOAT)) AS total_spend
FROM Tacos
WHERE NOT (PurchaseDate > '01/01/2016 12:00' OR '03/01/2016 12:00'< 
PurchaseDate)
GROUP BY
    CASE
        WHEN (COUNT('MerchantFamily' = %TacoTruck%)> 2) AND COUNT('MerchantFamily' != %TacoTruck%) >24)
            THEN 'Fanatic'
        WHEN (COUNT('MerchantFamily' = %TacoTruck%)> 2) AND COUNT('MerchantFamily' != %TacoTruck%) <24)
            THEN 'Loyalist'
        WHEN (COUNT('MerchantFamily' = %TacoTruck%)< 2) AND COUNT('MerchantFamily' != %TacoTruck%) <24)
            THEN 'Seldom'
        ELSE
            'Potential'    
    END

要么

GROUP BY
    CASE
        IF(COUNT(IF( 'MerchantFamily' = 'TacoTruck', 1, 0 ) ) > 2, TRUE, FALSE)
        AND 
        IF(COUNT(IF( 'MerchantFamily' != 'TacoTruck',1, 0) ) < 24, TRUE, FALSE), 'Loyalist', NULL )
        IF(COUNT(IF( 'MerchantFamily' = 'TacoTruck', 1, 0 ) ) > 2, TRUE, FALSE) 
        AND
        IF(COUNT(IF( 'MerchantFamily' != 'TacoTruck', 1, 0 ) ) > 24, TRUE, FALSE), 'Fanatic', NULL) 
        IF(COUNT(IF( 'MerchantFamily' = 'TacoTruck', 1, 0 ) ) < 2, TRUE, FALSE) 
        AND
        IF(COUNT( IF( 'MerchantFamily' != 'TacoTruck', 1, 0 ) ) < 24, TRUE, FALSE), 'Seldom', NULL) 
    ELSE
        'Potential'
END
答案

这些方法都不起作用,您需要先进行分组,然后通过having子句或嵌套子查询(“derived table”)来考虑聚合计数值。

case expression仅按行计算值,不扫描多行。

以上是关于将GROUP BY / CASE与WHEN或IF一起使用的主要内容,如果未能解决你的问题,请参考以下文章

关于case when结合group by用时的写法举例(转)

sql service (case when then else end ..... group by)

Oracle SQL - 使用 CASE WHEN 语句时 GROUP BY 无效

group by用法

mysql中的group_concat与“case when”条件

Sparklyr 使用 case_when 和变量