How to join multiple tables by date range in SQL?
我对SQL比较陌生。我一直在努力编写一个非常简单的查询,它返回一行。
我试图从几个不同的表中选择多个列值计数,每个计数都在相同的日期范围内。
我的数据库中的表如下所示:
1 2 3 4 5 | | CreationDate | LastName | EventType | |:--------------------|------------:|:------------:| ... | 2013-01-02 18:00:21 | Doe | 2 | | 2013-01-07 18:00:24 | Blanks | 2 | ... | 2013-01-09 17:00:21 | Puccini | 1 | |
所有表都有类似的creationdate列。
我现在的查询是一个像下面这样的单一联接(似乎可以工作)。我正在尝试添加一个或多个联接,以便可以将每个表的多个计数返回到单行结果中。我当前的查询:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | DECLARE @startdate DATETIME = '##startdate##'; DECLARE @enddate DATETIME = '##enddate##'; SELECT ISNULL(t2.Year, t1.Year) , ISNULL(t2.Month, t1.Month) , t1.LastName1 , t2.LastName2 FROM ( SELECT DATEPART(YEAR, table1.CreationDate) YEAR , DATEPART(MONTH, table1.CreationDate) MONTH , COUNT(table1.column2) LastName1 FROM table1 WHERE EventType = 2 AND CreationDate BETWEEN @startdate AND @enddate GROUP BY DATEPART(YEAR, table1.CreationDate) , DATEPART(MONTH, table1.CreationDate) ) AS t1 JOIN ( SELECT DATEPART(YEAR, table2.CreationDate) YEAR , DATEPART(MONTH, table2.CreationDate) MONTH , COUNT(table2.column2) LastName2 FROM table2 WHERE EventType = 1 AND CreationDate BETWEEN @startdate AND @enddate GROUP BY DATEPART(YEAR, table2.CreationDate) , DATEPART(MONTH, table2.CreationDate) ) AS t2 ON t1.Year = t2.Year AND t1.Month = t2.Month ORDER BY t1.Year , t1.Month |
我可以添加更多的连接吗?(我已经尝试过了,但还是有其他方法可以只返回每个选定列中指定日期范围内的计数(值)。
任何帮助都将不胜感激。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | DECLARE @startdate DATETIME SET @startdate= '2013-01-02 18:00:21.000'; DECLARE @enddate DATETIME SET @enddate= '2013-01-09 17:00:21.000'; SELECT YEAR , MONTH , [1] , [2] FROM ( (SELECT DATEPART(YEAR, CreationDate) YEAR , DATEPART(MONTH, CreationDate) MONTH , eventType , COUNT(LastName) namecount FROM table1 WHERE CreationDate BETWEEN @startdate AND @enddate GROUP BY DATEPART(YEAR, CreationDate) , DATEPART(MONTH, CreationDate) , EventType) UNION ALL (SELECT DATEPART(YEAR, CreationDate) YEAR , DATEPART(MONTH, CreationDate) MONTH , eventType , COUNT(LastName) namecount FROM table2 WHERE CreationDate BETWEEN @startdate AND @enddate GROUP BY DATEPART(YEAR, CreationDate) , DATEPART(MONTH, CreationDate) , EventType ) ) u PIVOT( SUM(namecount) FOR eventtype IN ( [1], [2] ) ) AS pvt ORDER BY YEAR , MONTH |
如果您想添加更多的事件类型,只需添加为([1]、[2]、[3]。)在
添加任意数量的表。