MySQL根据两个日期列之间的结果选择行

时间:2014-10-27 18:09:17

标签: mysql select datediff stacked

我有一张这样的表:

id | Type |   Date     |  DocDate
------------------------------
1  |  A   | 2014-04-05 | 2014-04-05
2  |  A   | 2014-05-06 | 2014-05-08
3  |  B   | 2014-06-06 | 2014-06-06

我需要创建一个堆叠的条形码。但要做到这一点,我需要将我的表转换为:

Type |  Green  |  Red
-----------------------
 A   |   1     |   1
 B   |   1     |   0

绿色和红色代表以下条件的结果:

IF (DocDate - Date) <= 1 THEN Green
IF (DocDate - Date) > 1  THEN Red

我尝试了这个查询:

SELECT CASE 
    WHEN (DocDate - Date) <= 1 THEN 'Green'
    WHEN (DocDate - Date) > 1 THEN 'Red'
END AS X, Count(OccurrenceID) AS Total
FROM tbloccurrence
GROUP BY CASE
    WHEN (DocDate - Date) <= 1 THEN 'Green'
    WHEN (DocDate - Date) > 1 THEN 'Red'
END;

但结果不是我需要的。有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

我开始编写一个查询,从表中拉出每一行,并分配绿色或红色列。为此,您可以使用IF()语句。这需要3个参数:条件,如果条件为真则该怎么办,以及如果该条件为假则该怎么办。这给了我们这个:

SELECT type, IF(DATEDIFF(docdate, dateCol) <= 1, 1, 0) AS green, IF(DATEDIFF(docdate, dateCol) > 1, 1, 0) AS red
FROM myTable;

我还使用了DATEDIFF()功能。这将返回两个参数之间的整数天数(需要DATE或DATETIME参数)。

然后,我只是将红色和绿色列相加并按类型分组以匹配您的结果集:

SELECT type, SUM(IF(DATEDIFF(docdate, dateCol) <= 1, 1, 0)) AS green, SUM(IF(DATEDIFF(docdate, dateCol) > 1, 1, 0)) AS red
FROM myTable
GROUP BY type;

以下是免费的SQL Fiddle