0

我有一个查询问题:我有一个表格,其中列出了客户下的订单

orders: customer_id, payment_method ...some other field

如果客户使用特定付款方式进行了至少一次付款,我需要提取 customer_id 和“YES”

我试过这样的事情:

SELECT DISTINCT o.customer_id, 
CASE WHEN o.payment_method = 10 THEN 'YES' ELSE 'NO' END AS credit_card
FROM orders AS o
WHERE o.year = 2012
ORDER BY o.customer_id

但是如果客户使用不同的付款方式付款,则会显示两条记录,一条为“YES”,一条为“NO”……有可能只得到一个值吗?

4

2 回答 2

2
SELECT   o.customer_id, 
         IF(MAX(IF(o.payment_method=10, 1, 0)) = 1, 'YES', 'NO') credit_card
FROM     orders o
WHERE    o.year = 2012
GROUP BY o.customer_id
于 2012-07-19T16:22:48.490 回答
0

您可以使用 group by 进行自联接并在联接表中测试 NULL(未经测试):

SELECT customer_id, IF(p.customer_id IS NULL, 'NO', 'YES')
FROM orders o
LEFT OUTER JOIN orders p ON o.customer_id = p.customer_id AND p.payment_method = 10
    AND p.year = 2012
WHERE o.year = 2012
GROUP BY o.customer_id
ORDER BY o.customer_id

不确定您是否需要该p.year = 2012条件。

于 2012-07-19T16:23:56.750 回答