从mysql中的datewise数据获取逐月行计数

时间:2017-12-24 12:19:54

标签: php mysql mariadb

我有两张桌子:

 table 1.a
    id--entry_date-amount
============================
    2---2016-04-14--$400
    3---2016-04-14--$400
    4----2017-07-14--$200
    5---2017-07-14--$500
    6---2017-05-14--$600
    7----2017-06-18--$100

    table 2.b
    id--entry_date
===========================
    2---2016-04-14--$230
    3---2016-04-14--$230
    4----2017-07-14--$567
    5---2017-07-14--$600
    6---2017-05-14--$560
    7----2017-06-18--$90
    8---2016-04-14--$100

从两个表中我怎么能用montwise计算 我想要的结果:

month_name--total(count form table a)--total(count form table b)--amount(table a)--amount(table b)
========================================================
April,16-----------2-------------------3---$800-$500
May,17-----------1-------------------1 --$600--$700
June,17-----------2-------------------2--$100--$800
July,17-----------2-------------------2---$700-$400

这是演示数据。 我希望在一个月的单个查询中显示来自两个表的数据。 我怎么能这样做?

我试过了:

SELECT MONTHNAME(r.entry_date),r.a_total FROM( 
SELECT
IFNULL((SELECT COUNT(tr.id) AS amount FROM a AS tr WHERE MONTH(tr.entry_date)=MONTH(t.entry_date)),0) AS a_total
,t.entry_date

FROM(SELECT tr.id,tr.entry_date
 FROM a AS tr
 WHERE DATE(tr.entry_date) BETWEEN '2017-07-01' AND '2018-06-30') t

   GROUP BY MONTH(t.entry_date)) r

但简单查询需要58秒。我怎样才能在一个简单的查询中做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以单独从每个表中获取计数和总和,然后使用UNION将两个结果集合并为一个结果集。像这样:

SELECT Month_name,
  SUM(aCount) AS aCount,
  SUM(bCount) AS bCount,
  SUM(aAmount) AS aAmount,
  SUM(bAmount) AS bAmount
FROM
(
  SELECT  
    MONTHNAME(a.entry_date) AS Month_name,
    COUNT(a.id) AS aCount,
    0 AS bCount,
    SUM(a.amount) AS aAmount,
    0 AS bAmount
  FROM a
  GROUP BY MONTHNAME(a.entry_date)
  UNION ALL
  SELECT  
    MONTHNAME(b.entry_date) AS Month_name,
    0 AS aCount,
    COUNT(b.id) AS bCount,
    0 AS aAmount,
    SUM(b.amount) AS bAmount
  FROM b
  GROUP BY MONTHNAME(b.entry_date)
) AS t
GROUP BY Month_Name;

live demo

答案 1 :(得分:0)

user9131497具有良好的全局设计。但是,我建议这样处理日期:

SELECT  DATE_FORMAT(entry_date, "%M,%y") AS 'Month',
        COUNT(*) AS 'aCount'
    FROM a
    GROUP BY LEFT(entry_date, 7)  -- eg, "2017-03"

试试看我的意思。

请注意,这将超过一年。或者您是否需要将所有年份的1月值合并? - 这就是你的解决方案和user9131497的功能。我将它们分开。