WITH Deal AS ( SELECT YEAR(CREATED_TIME) 'YEAR',MONTH(CREATED_TIME) 'MONTH',t1.*,CATEGORY,t2.ACCOUNT_NAME 'ACCOUNT_NAMEs',t2.QUADRANT,t2.GRADE 'AGRADE',t2.MODEL_RELATED_DEGREE from CRM_DEALS t1 left JOIN CRM_ACCOUNTS t2 ON t1.ACCOUNT_ID = t2.ID WHERE LEFT(QUADRANT, 1) IN(1,4) AND SOURCE IN ('摩点','KS','GameFound','Indiegogo','Backerkit','BGG') ) SELECT YEAR,MONTH,COUNT(DISTINCT ACCOUNT_NAMEs) '月度实际值',SUM(COUNT(DISTINCT ACCOUNT_NAMEs)) OVER(PARTITION BY YEAR ORDER BY YEAR, MONTH) AS '月度累计值' FROM Deal WHERE YEAR = YEAR(GETDATE()) AND (YEAR < YEAR(GETDATE()) OR (YEAR = YEAR(GETDATE()) AND MONTH <= MONTH(GETDATE()))) GROUP BY YEAR, MONTH; 这段sql查询6月没有数据,怎么补全
时间: 2023-12-24 21:04:42 浏览: 153
如果该SQL查询6月没有数据,可以使用以下两种方式进行补全:
1. 使用OUTER JOIN将CRM_DEALS表的所有月份都查询出来,并将COUNT和SUM函数的返回值设置为0,以保证所有月份都有数据输出。
```
WITH Deal AS (
SELECT YEAR(CREATED_TIME) 'YEAR',
MONTH(CREATED_TIME) 'MONTH',
t1.*,
CATEGORY,
t2.ACCOUNT_NAME 'ACCOUNT_NAMEs',
t2.QUADRANT,
t2.GRADE 'AGRADE',
t2.MODEL_RELATED_DEGREE
FROM CRM_DEALS t1
LEFT JOIN CRM_ACCOUNTS t2 ON t1.ACCOUNT_ID = t2.ID
WHERE LEFT(QUADRANT, 1) IN (1,4)
AND SOURCE IN ('摩点','KS','GameFound','Indiegogo','Backerkit','BGG')
)
SELECT YEAR,
MONTH,
COUNT(DISTINCT ACCOUNT_NAMEs) '月度实际值',
SUM(COUNT(DISTINCT ACCOUNT_NAMEs)) OVER(PARTITION BY YEAR ORDER BY YEAR, MONTH) AS '月度累计值'
FROM (
SELECT DISTINCT YEAR, MONTH
FROM Deal
WHERE YEAR = YEAR(GETDATE())
AND (YEAR < YEAR(GETDATE()) OR (YEAR = YEAR(GETDATE()) AND MONTH <= MONTH(GETDATE())))
) t1
LEFT JOIN Deal t2 ON t1.YEAR = t2.YEAR AND t1.MONTH = t2.MONTH
GROUP BY YEAR, MONTH;
```
2. 使用UNION ALL将查询结果中没有数据的月份手动添加到结果集中,并将COUNT和SUM函数的返回值设置为0。
```
WITH Deal AS (
SELECT YEAR(CREATED_TIME) 'YEAR',
MONTH(CREATED_TIME) 'MONTH',
t1.*,
CATEGORY,
t2.ACCOUNT_NAME 'ACCOUNT_NAMEs',
t2.QUADRANT,
t2.GRADE 'AGRADE',
t2.MODEL_RELATED_DEGREE
FROM CRM_DEALS t1
LEFT JOIN CRM_ACCOUNTS t2 ON t1.ACCOUNT_ID = t2.ID
WHERE LEFT(QUADRANT, 1) IN (1,4)
AND SOURCE IN ('摩点','KS','GameFound','Indiegogo','Backerkit','BGG')
)
SELECT YEAR,
MONTH,
COUNT(DISTINCT ACCOUNT_NAMEs) '月度实际值',
SUM(COUNT(DISTINCT ACCOUNT_NAMEs)) OVER(PARTITION BY YEAR ORDER BY YEAR, MONTH) AS '月度累计值'
FROM (
SELECT DISTINCT YEAR, MONTH
FROM Deal
WHERE YEAR = YEAR(GETDATE())
AND (YEAR < YEAR(GETDATE()) OR (YEAR = YEAR(GETDATE()) AND MONTH <= MONTH(GETDATE())))
UNION ALL
SELECT YEAR(GETDATE()) AS YEAR, 6 AS MONTH
) t1
LEFT JOIN Deal t2 ON t1.YEAR = t2.YEAR AND t1.MONTH = t2.MONTH
GROUP BY YEAR, MONTH;
```
阅读全文