CASE 语句而不是内部连接

CASE Statement instead of inner join

这是我的 table 结构:

CUST_ID  ORDER_MONTH
---------------------
 1       1
 1       5
 2       3
 2       4

我的 objective 是将这些客户标记为新客户或回头客。

当我过滤第 1 个月的查询时,客户 1 应该有标签 'New',但是当我过滤第 5 个月的查询时,客户 1 应该显示为 'Return',因为他已经在第 1 个月进行了购买。

客户 ID 2 应以同样的方式在第 3 个月显示为新用户,在第 ​​4 个月显示为 return。

我想使用 CASE 语句而不是内部联接来执行此操作。

谢谢

您不需要 JOIN 并且 case 语句可能会过大...

SELECT CUST_ID, IF(COUNT(1)>1, 'Returning', 'New') AS blah
FROM the_table
WHERE ORDER_MONTH <= the_month
GROUP BY CUST_ID
;

当然,仅使用月份会在一年后(或者实际上,在过了 12 月之后)出现问题。

这样会更好

SELECT CUST_ID, IF(COUNT(1)>1, 'Returning', 'New') AS blah
FROM the_table
WHERE order_date <= some_date
GROUP BY CUST_ID
;

嗯,我不推荐这种方式,但这就是你想要的。

select *
,case when order_month = (select MIN(order_month) from #temp t2 where t1.cust_ID =t2.cust_id) THEN 'NEW' ELSE 'Return' end 'Type'
from #temp t1

我想我明白你想要做什么。您的案例陈述基本上只需要检查客户的月份是否等于您筛选的月份。像这样:

SELECT 
<your other fields>,
CASE WHEN Order_Month = <your filter> THEN 'New'   
    ELSE 'Return' 
    END  AS 'SomeName'
FROM <your table>

试试这个查询

select a.CUST_ID,  a.ORDER_MONTH ,case when b is not null then 'Return' else 'New' end as type
 from tablename a
join tablename b on a.CUST_ID=b.CUST_ID and a.ORDER_MONTH>b.ORDER_MONTH

如果你坚持使用case语句,逻辑会是这样"If this is the first month for that user, write new, otherwise write returning."查询会是这样:

SELECT CASE 
   WHEN m.month = (SELECT MIN(month) FROM myTable WHERE customer = m.customer) THEN 'New' 
   ELSE 'Returning' END AS customerType
FROM myTable m;

不过,我认为在 JOIN 中这会更好、更易读。您可以编写聚合查询以获取每个用户的最早月份,然后使用 COALESCE() 将空值替换为 'Returning'。聚合:

SELECT customer, MIN(month) AS minMonth, 'New' AS customerType
FROM myTable
GROUP BY customer ;

要得到其余的:

SELECT m.customer, m.month, COALESCE(t.customerType, 'Returning') AS customerType
FROM myTable m
LEFT JOIN(
   SELECT customer, MIN(month) AS minMonth, 'New' AS customerType
   FROM myTable
   GROUP BY customer) t ON t.customer = m.customer AND t.minMonth = m.month;

这是一个显示这两个示例的 SQL Fiddle 示例。

SELECT *, 
   CASE 
     WHEN EXISTS (SELECT * 
                  FROM   [YourTable] t2 
                  WHERE  t1.cust_id = t2.cust_id 
                         AND t2.order_month < t1.order_month) THEN 'Return' 
     ELSE 'New' 
   END
FROM   [YourTable] t1 

此查询在 EXISTS 子句上使用 CASE。 EXISTS 位于一个子查询上,该子查询对前几个月的任何行查询相同的 table。 如果有前几个月的行,则 EXISTS 为真且 CASE returns 'Return'。如果前几个月没有行,则 EXISTS 为假,CASE returns 'New'.