我在SQL中有一个具有多个条件的Case When语句,我需要以正确的顺序评估条件。 这是我的代码。
SELECT company_id,
MIN(CASE WHEN number_of_orders >= 10 THEN order_month
WHEN number_of_orders >= 1 AND number_of_orders < 10 THEN order_month
ELSE NULL END) AS first_month_with_many_orders
FROM monthly_orders
我需要首先评估number_of_orders&gt; = 10的第一个条件。这段代码似乎没有完成这个,因为我有一些公司有月份满足这两个条件,所以它返回满足第一个条件的最小月份。但是,我真正想要的是&gt; = 10个订单的最低月份,我只希望第二个条件适用于没有超过10个订单的月份的公司。
那么如何才能获得第一个被评估的条件,然后只有在第二个条件失败时才会进入第二个条件?
答案 0 :(得分:0)
首先,在order_month
和number_of_orders >= 10
两种情况下,您的SQL案例都会返回number_of_orders >= 1 AND number_of_orders < 10
。这可能是错的,不确定。
其次,我推荐一个子查询,如下所示:
SELECT company_id, MIN(theSubquery.month_with_many_orders) as first_month_with_many_orders
FROM (
SELECT company_id,
CASE WHEN number_of_orders >= 10 THEN order_month
WHEN number_of_orders >= 1 AND number_of_orders < 10 THEN order_month
ELSE NULL END) AS month_with_many_orders
) AS theSubquery
我不确定正确的细节,因为没有提供更多信息。但通常情况下,我会让子查询允许制作更清晰的步骤。您甚至可以摆脱CASE并在子查询中使用WHERE,这将更具可读性。
答案 1 :(得分:0)
试图得到你所写的内容:
如果我是对的,那么SQL将是:
SELECT
company_id,
IsNull((SELECT MIN(order_month) FROM monthly_orders WHERE company_id = A.company_id and number_of_order >= 10),(SELECT MIN(order_month) FROM monthly_orders WHERE company_id = A.company_id and number_of_order >= 1 and number_of_order < 10))
FROM monthly_orders A
GROUP BY company_id
更新
另一个问题是
SELECT
A.company_id,
min(case when MAX_ORDER = 0 then NULL ELSE order_month END) first_month_with_many_orders
FROM monthly_orders A
INNER JOIN (SELECT company_id, MAX(number_of_order) MAX_ORDER FROM monthly_orders GROUP BY company_id) as B
ON A.company_id = B.company_id
AND number_of_order >= (CASE WHEN MAX_ORDER >= 10 THEN 10 WHEN MAX_ORDER >=1 THEN 1 ELSE 0 END)
GROUP BY A.company_id