如何获得MySQL中第一季度的第一个日期?

时间:2012-08-09 13:32:54

标签: mysql date

我到目前为止的代码如下:我正在试图找出代替我的代码来查找日期所在季度的开始日期。

SELECT
 QUARTER(r.callDate) AS quar,
 YEAR(r.callDate) AS ryear,
 ???????? AS scoreDateStart,
 (SELECT DATE (DATE_SUB( DATE_ADD( CONCAT( YEAR( r.callDate ), '-01-01'), INTERVAL QUARTER(r.callDate) QUARTER ), INTERVAL 1 DAY))) AS scoreDateEnd,
 group_concat(DISTINCT(r.resultId) separator ', ') AS resultIds
FROM results AS r
GROUP BY  quar, ryear
ORDER BY quar;

我尝试过谷歌搜索,但无济于事。

输出的一个例子是:

'1', '2012', '2012-01-01', '2012-03-31', '57, 58, 59'
'2', '2012', '2012-04-01', '2012-06-30', '10549, 10551, 12598'

1 个答案:

答案 0 :(得分:18)

试试这个:

要获取当前季度的开始日期,请使用:

  SELECT  MAKEDATE(YEAR(CURDATE()), 1) + INTERVAL QUARTER(CURDATE()) QUARTER 
                                       - INTERVAL    1 QUARTER 

所以你的查询将是:

SELECT
 QUARTER(r.callDate) AS quar,
 YEAR(r.callDate) AS ryear,
 MAKEDATE(YEAR(r.callDate), 1) + INTERVAL QUARTER(r.callDate) QUARTER -
  INTERVAL 1 QUARTER  AS scoreDateStart,
 (SELECT DATE (DATE_SUB( DATE_ADD( CONCAT( YEAR( r.callDate ), '-01-01'), 
 INTERVAL QUARTER(r.callDate) QUARTER ), INTERVAL 1 DAY))) AS scoreDateEnd,
 group_concat(DISTINCT(r.resultId) separator ', ') AS resultIds
FROM results AS r
GROUP BY  quar, ryear
ORDER BY quar;