使用MySQL Case比较日期

时间:2014-04-07 02:34:15

标签: mysql case

我需要将三个表中的数据制成表格以用于报告。请参阅此查询

SELECT
    DATE( sale.sale_time ) AS dat,
    location.location_name as location,
    sale.sale_id AS total_orders, 
    SUM( CASE sale.is_cancelled WHEN 0 THEN sale.sale_amount   ELSE 0 END ) AS sales, 
    SUM( CASE sale.is_cancelled WHEN 0 THEN sale.sale_discount ELSE 0 END ) AS discounts,
    SUM( CASE sale.is_cancelled WHEN 0 THEN sale.sale_tax      ELSE 0 END ) AS taxes, 
    COUNT( DISTINCT sale.customer_id ) AS total_customers, 
    SUM( CASE WHEN DATE( person.added_on ) = DATE( sale.sale_time ) THEN 1 ELSE 0 END ) AS new_customers,
    SUM( CASE sale.is_cancelled WHEN 1 THEN 1 ELSE 0 END ) AS cancelled_orders
FROM
    sales AS sale
    INNER JOIN locations AS location ON location.location_id = sale.location_id
    INNER JOIN people    AS person   ON     person.person_id = sale.customer_id
GROUP BY
    dat,location

new_customers的结果显示错误,通常超过total_customers。错在哪里,如何纠正?

结果是这样的:

    dat location    total_orders    sales   discounts   taxes   new_customers   total_customers cancelled_orders
15-03-14    Location1   52  1355    0   129.04  4   2   0
16-03-14    Location1   56  280 0   30  2   1   0
16-03-14    Location2   59  2518    0   212.2   3   6   2

正如您可能从查询中猜到的那样,sales表的列包含sale_id,sale_time,sale_cost,sale_discount,sale_tax,sale_amount,is_cancelled(tinyint,其值为0或1)和customer_id

People表的列为person_id,first_name,added_on

通过将日期(salessale_time)与日期(person.added_on)进行比较,我想列出在该日期添加的客户

1 个答案:

答案 0 :(得分:1)

我将查询修改为以下内容,以便在结果集中获得新客户。

SELECT DATE(sale.sale_time) AS dat, location.location_name as location, (sale.sale_id) AS total_orders, 
SUM(CASE sale.is_cancelled WHEN 0 THEN sale.sale_amount ELSE 0 END) AS sales, 
SUM(CASE sale.is_cancelled WHEN 0 THEN sale.sale_discount ELSE 0 END) AS discounts,
SUM(CASE sale.is_cancelled WHEN 0 THEN sale.sale_tax ELSE 0 END) AS taxes, 
count(distinct(sale.customer_id)) AS total_customers, 
(select count(person_id) from people where date(added_on) = date(sale.sale_time) and person_id = sale.customer_id) as new_customers,
SUM(CASE sale.is_cancelled WHEN 1 THEN 1 ELSE 0 END) AS cancelled_orders
FROM sales AS sale
INNER JOIN locations AS location ON location.location_id = sale.location_id
GROUP BY dat,location;