SQL符合我的要求?

时间:2010-12-30 15:48:32

标签: mysql

我需要一个SQL查询来列出过去6个月内加入的所有客户。

这是我的SQL。

    select 
    c.company_name,
    c.phone1,
    c.sprovince,
    c.scountry,
    sum(order_total_amount) as amt_sold,
    max(o.order_date) as last_order_date,
    customersince
from
        tbl_company c
join
        tbl_order o
    on c.companyid = o.company_id
where
    c.companytype like 'Customer'
and
    (PERIOD_DIFF(c.customersince,curdate())<6)
group by company_name
order by amt_sold desc

现在我还需要一个或条件,以便如果客户列中的空值为null,那么我应该检查客户的第一个订单。如果是在过去6个月,我也应该显示该用户。

order_date在tbl_order表中可用。客户的第一个订单是customer(id_date)group by customer_id

我该怎么做?

3 个答案:

答案 0 :(得分:1)

PERIOD_DIFF(ifnull(c.customersince, `first_order`),curdate())<6)

你应该包括你的表架构,你的第一个订单是参考哪个表?

答案 1 :(得分:1)

SELECT  c.company_name,
        c.phone1,
        c.sprovince,
        c.scountry,
        SUM(order_total_amount) as amt_sold,
        MAX(o.order_date) as last_order_date,
        COALESCE(customersince, MIN(o.order_date)) AS customersince
FROM    tbl_order o
JOIN    tbl_company c
ON      c.companyid = o.company_id
WHERE   c.companytype like 'Customer'
        AND (c.customersince >= NOW() - INTERVAL 6 MONTH OR c.customersince IS NULL)
GROUP BY
        companyid
HAVING  customersince >= NOW() - INTERVAL 6 MONTH
ORDER BY
        amt_sold DESC

注意customersince上的双重条件:WHERE子句中的一个,HAVING子句中的另一个。

如果您在tbl_customer (customersince)上有索引,则此索引将用于提前过滤相应的记录(并在以后对其进行精细过滤)。

答案 2 :(得分:0)

我没有要测试的mysql,但是这个where子句可能适合你:

where c.companytype like 'customer' 
and ( 
    (PERIOD_DIFF(c.customersince, curdate())<6)
    OR
    (c.customersince is null AND (PERIOD_DIFF(o.order_date, curdate())<6)
)

此外,您必须在聚合函数(max,sum等)中添加您没有的东西到group by子句。