在mysql中显示周日期范围以及周总结

时间:2015-04-15 10:27:58

标签: mysql sql

我正在为我的项目准备一份报告,我将根据单一列显示前4周的摘要。这是我的询问。

`SELECT `TBL33_ORGID`,
/* Trend DAK calcualation */
SUM(IF(WEEK(`tbl33_date`) = '12', `TBL33_DAK`, 0)) AS week_1st_dak,
SUM(IF(WEEK(`tbl33_date`) = '13', `TBL33_DAK`, 0)) AS week_2nd_dak,
SUM(IF(WEEK(`tbl33_date`) = '14', `TBL33_DAK`, 0)) AS week_3rd_dak,
SUM(IF(WEEK(`tbl33_date`) = '15', `TBL33_DAK`, 0)) AS week_4th_dak,
FROM `tbl33_snapshotorg`
WHERE   YEAR(`tbl33_date`) = '2015'
AND  (WEEK(`tbl33_date`) = '12' OR WEEK(`tbl33_date`) = '13' OR WEEK(`tbl33_date`) = '14'  OR WEEK(`tbl33_date`) = '15' )
GROUP BY `TBL33_ORGID``

我的查询输出很好,但现在我需要显示周开始日期和结束日期。     我已经尝试过以下方式,但效果不佳。

`IF(WEEK(`tbl33_date`) = '12',MIN(`tbl33_date`),null) AS week_1st_start, 
IF(WEEK(`tbl33_date`) = '12',MAX(`tbl33_date`),null) AS week_1st_end,

IF(WEEK(`tbl33_date`) = '13',MIN(`tbl33_date`),null) AS week_2nd_start, 
IF(WEEK(`tbl33_date`) = '13',MAX(`tbl33_date`),null) AS week_2nd_end,

IF(WEEK(`tbl33_date`) = '14',MIN(`tbl33_date`),null) AS week_3rd_start, 
IF(WEEK(`tbl33_date`) = '14',MAX(`tbl33_date`),null) AS week_3rd_end,

IF(WEEK(`tbl33_date`) = '15',MIN(`tbl33_date`),null) AS week_4th_start, 
IF(WEEK(`tbl33_date`) = '15',MAX(`tbl33_date`),null) AS week_4th_end `

如何在不进行任何额外查询的情况下实现这一目标。

1 个答案:

答案 0 :(得分:1)

你想在条件表达式里面聚合函数 - “条件聚合”:

SELECT MIN(CASE WHEN tbl33_date = 12 THEN tbl33_date END) as week_1st_start,
       MAX(CASE WHEN tbl33_date = 12 THEN tbl33_date END) as week_1st_end,
       . . .