如何计算mysql中的两个日期范围

时间:2017-06-22 01:02:10

标签: mysql

我必须通过php excel导出excel 1张纸具有不同的日期范围计数值,

example:
SELECT count(*) as week_service_times FROM
        (
            SELECT  d.wkdetid,m.eqpid as eqpid,m.assetno as assetno,m.kindname as kindname,m.custname as custname,m.brandname as brandname,e.custname_short as custname_short
            FROM    WKMast as m
            INNER JOIN WKDet as d USING(wkid)
            INNER JOIN DeptCust as e on m.custid = e.custid and m.zoneid = e.zoneid and m.deptid = e.deptid
            LEFT JOIN HandleCode as h on d.causecode = h.causecode and d.hdlcode = h.hdlcode
            LEFT JOIN EQPMast as E on E.eqpid = m.eqpid
            WHERE   m.gpid_p = 'gp02'
            AND     (m.typeid = 'tp01')
            AND     date(m.s_time) BETWEEN '2017-06-01' AND '2017-06-18'
            GROUP BY d.wkdetid
            ORDER BY date(m.s_time)
        ) AS T1
        GROUP BY eqpid    

我的约会(m_stime)BETWEEN' 2017-06-01'和' 2017-06-18'

但我必须实施其他日期范围,例如BETWEEN' 2017-06-12'和' 2017-06-18'

第二个日期范围必须在第一个数据范围

可以帮助我在一个sql中实现它吗?

导出数据

Serial NO   2017-06-01 TO 2017-06-18    2017-06-12 TO 2017-06-18
5300077120  5                                 3
5300097135  4                                 2

1 个答案:

答案 0 :(得分:1)

您可以使用带有SUM()或COUNT()的MySQL IF,如下所示。

            COUNT(IF(date >= '2017-06-01' AND date <= '2017-06-18', 1, null)) AS range1,
            COUNT(IF(date >= '2017-06-01' AND date <= '2017-06-12', 1, null)) AS range2