不要使用mysql从两个表中选择数据库中的数据

时间:2014-08-21 09:53:07

标签: mysql

我有2张桌子的销售和收据。表格结构和结果结构如下所示。

促销

date          total     sale_type

15-8-2014      50       credit

16-8-2014      100      credit

17-8-201       200      return

18-8-2014      300      return

收据

  date           net_amount


  15-8-2014         100

  16-8-2014         200

  17-8-2014         300

结果

date            sale      receipt


15-8-2014       50         100

16-8-2014       100        200

17 -8-2014      200        300

18-8-2014       300 

使用我的查询我得到了这些结果结构,但我想得到案例中的总和sales_type ='credit'和sale_type ='return“。任何身体帮助我吗?

我的查询是

    select date,total,net_amount from
     (select  date, total, null as net_amount, 2 as sort_col from sale union
all select date, 
null as total, net_amount as net_amount, 1 as sort_col from receipt)
 as a order by date desc, sort_col desc

1 个答案:

答案 0 :(得分:0)

以下查询(使用JOINCASE是否可以获得预期结果?

SELECT
    s.date,
    s.total AS sale,
    r.net_amount AS receipt,
    SUM(CASE
        WHEN s.sale_type = 'credit' THEN s.total
        ELSE 0
    END) AS sum_credit,
    SUM(CASE
        WHEN s.sale_type = 'return' THEN s.total
        ELSE 0
    END) AS sum_return
FROM sale s
LEFT JOIN receipt r
ON s.date = r.date
GROUP BY s.date, s.total, r.net_amount;