---
title: "关联dim_date表，使日期连续"
author: "jveqi"
date: "2016-05-13T18:42:46Z"
tags: []
categories: ["数据库"]
slug: "dim-date"
draft: false
lastmod: "2016-06-17T10:03:32Z"
id: 2298075
url: "https://balzac.iteye.com/blog/2298075"
---

MYSQL:

1、报表需要展示连续每天的数据，但业务数据可能是间断的，故关联dim\_date表，使日期连续

CREATE TABLE \`dim\_date\` (

  \`date\_key\` int(11) NOT NULL,

  \`date\_value\` date DEFAULT NULL,

  \`week\_in\_year\` int(11) DEFAULT NULL,

  \`week\_in\_month\` int(11) DEFAULT NULL,

  \`month\_number\` int(11) DEFAULT NULL,

  \`quarter\_number\` int(11) DEFAULT NULL,

  \`day\_in\_year\` int(11) DEFAULT NULL,

  \`day\_in\_month\` int(11) DEFAULT NULL,

  \`year\` int(11) DEFAULT NULL,

  \`month\` int(11) DEFAULT NULL,

  \`day\` int(11) DEFAULT NULL,

  PRIMARY KEY (\`date\_key\`),

  KEY \`date\_value\_idx\` (\`date\_value\`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、动态拼接年月日、然后分组

 

 

SELECT

&lt;if test="type == 1"&gt;  

DATE(CONCAT(d.YEAR, '-', d.MONTH, '-', d.DAY)) 

   &lt;/if&gt; 

&lt;if test="type == 2"&gt;  

DATE(CONCAT(d.YEAR, '-', d.MONTH, '-1'))  

   &lt;/if&gt; 

&lt;if test="type == 3"&gt;  

DATE(CONCAT(d.YEAR, '-1-1')) 

   &lt;/if&gt; 

&lt;if test="type == 4"&gt;  

DATE(CONCAT(d.YEAR, '-', d.MONTH, '-', d.DAY)) 

   &lt;/if&gt; 

   AS statdate,

SUM(a.order\_num) AS order\_num,

SUM(a.amount) AS amount,

SUM(a.validincome) AS validincome

FROM

dim\_date d LEFT JOIN s\_orderscount\_day a on d.date\_value = a.stat\_date 

&lt;if test="fcId=='' and groupId==null"&gt; 

AND a.finance\_category\_id = -1  

&lt;/if&gt;

&lt;if test="fcId!='' or groupId!=null"&gt; 

AND a.finance\_category\_id != -1  

&lt;/if&gt;

 

&lt;if test="channel != null and channel != '' "&gt; 

AND a.sale\_channel= #{channel}

&lt;/if&gt;

&lt;if test="fcId != null and fcId != ''"&gt; 

AND FIND\_IN\_SET(a.finance\_category\_id, #{fcId})

&lt;/if&gt;

&lt;if test="fcId!='' or groupId!=null"&gt; 

LEFT JOIN products p 

ON

a.finance\_category\_id = p.oldid  and a.product\_group\_id = p.groupid 

&lt;/if&gt;

&lt;if test="groupId != null and groupId != '' "&gt; 

AND a.finance\_category\_id != -1 

AND p.groupid = #{groupId}

&lt;/if&gt;

WHERE 1=1 

AND d.date\_value &lt;!\[CDATA\[&gt;=]]&gt; #{startTime}

AND d.date\_value &lt;!\[CDATA\[&lt;=]]&gt; #{endTime}

GROUP BY

statdate