gpt4 book ai didi

sql - 如何在 SQL 中按日期范围连接多个表?

转载 作者:行者123 更新时间:2023-12-02 19:10:55 26 4
gpt4 key购买 nike

我对 SQL 比较陌生。我一直在努力编写一个返回单行的非常简单的查询。

我正在尝试从多个不同的表中选择多个列值计数,每个计数都是针对同一日期范围提取的。

我的数据库中的表类似于:

|   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 列。

我现在的查询是像下面这样的单个 JOIN (这似乎有效)。我正在尝试添加一个或多个 JOIN,以便我可以将每个表的更多计数返回到单行结果。我当前的查询:

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

我可以添加更多 JOIN 吗? (我已经尝试过,但被绊倒了。)或者是否有另一种方法可以仅返回每个选定列中指定日期范围内的 COUNT(值)。

如有任何帮助,我们将不胜感激。

最佳答案

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]..)在 PIVOT() 内,也在 SELECT

添加任意数量的表。

关于sql - 如何在 SQL 中按日期范围连接多个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22031932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com