CASE WHEN - 多个条件 - 同一参考的多行
CASE WHEN - Multiple Conditions - Over Multiple Rows of same reference
我正在尝试通过使用 CASE WHEN 来确定某些内容来创建一个标志,但它一直返回“single_state” - 我猜是因为它没有将 CASE WHEN 应用于所有具有 o/n 1234 的行这是我需要帮助的一点。
我的预期输出是前 3 行是“multi_state”,因为它们都是相同的 o/n,最后一行是“single_state”,因为它们都没有分组或获得超过 1 个状态。
示例如下:
数据Table
o/n sku order_type state state_check
1234 ABC987 Grouped express
1234 BCD654 Grouped arrived
1234 CDF321 Grouped shipped
5679 GBT104 Not Grouped express
查询
SELECT o/n, SKU, order_type, state,
CASE WHEN order_type is "Grouped" AND (state = "express" AND state = "arrived") THEN "multi_state"
CASE WHEN order_type is "Grouped" AND (state = "express" AND state = "shipped") THEN "multi_state"
ELSE "single_state"
END AS state_check
FROM data.table
multi_state
的 CASE
都检查 state
是否同时具有值 express
和 arrived
/shipped
.单个列不能同时有多个值。
您可以使用 IN()
接受多个值,如 multi_state
:
SELECT o/n
, sku
, order_type
, state
, CASE
WHEN order_type = 'Grouped' AND state IN('express', 'arrived', 'shipped') THEN 'multi_state'
ELSE 'single_state'
END AS state_check
FROM data.table
您需要一个 window 函数(一个带有 OVER
子句的聚合函数)来一次查看多行。
SELECT
"o/n", sku, order_type, state,
CASE
WHEN order_type <> 'Grouped' THEN
'single_state'
WHEN COUNT(DISTINCT state) OVER (PARTITION BY "o/n", order_type) = 1 THEN
'single_state'
ELSE
'multi_state'
END
FROM data.table
ORDER BY "o/n", sku;
我正在尝试通过使用 CASE WHEN 来确定某些内容来创建一个标志,但它一直返回“single_state” - 我猜是因为它没有将 CASE WHEN 应用于所有具有 o/n 1234 的行这是我需要帮助的一点。
我的预期输出是前 3 行是“multi_state”,因为它们都是相同的 o/n,最后一行是“single_state”,因为它们都没有分组或获得超过 1 个状态。
示例如下:
数据Table
o/n sku order_type state state_check
1234 ABC987 Grouped express
1234 BCD654 Grouped arrived
1234 CDF321 Grouped shipped
5679 GBT104 Not Grouped express
查询
SELECT o/n, SKU, order_type, state,
CASE WHEN order_type is "Grouped" AND (state = "express" AND state = "arrived") THEN "multi_state"
CASE WHEN order_type is "Grouped" AND (state = "express" AND state = "shipped") THEN "multi_state"
ELSE "single_state"
END AS state_check
FROM data.table
multi_state
的 CASE
都检查 state
是否同时具有值 express
和 arrived
/shipped
.单个列不能同时有多个值。
您可以使用 IN()
接受多个值,如 multi_state
:
SELECT o/n
, sku
, order_type
, state
, CASE
WHEN order_type = 'Grouped' AND state IN('express', 'arrived', 'shipped') THEN 'multi_state'
ELSE 'single_state'
END AS state_check
FROM data.table
您需要一个 window 函数(一个带有 OVER
子句的聚合函数)来一次查看多行。
SELECT
"o/n", sku, order_type, state,
CASE
WHEN order_type <> 'Grouped' THEN
'single_state'
WHEN COUNT(DISTINCT state) OVER (PARTITION BY "o/n", order_type) = 1 THEN
'single_state'
ELSE
'multi_state'
END
FROM data.table
ORDER BY "o/n", sku;