我有一个表 IPAddressHistory 表,该表包含三列 IPAddressID , DateFrom 和 DateTo ,以及另一个表 IPAddressTimeValue ,其中包含特定时间的详细值。因此,我需要从 IPAddressID到 Date之间的 IPAddressID 和 IPAddressID 相关的 IPAddressTimeValue 中选择SUM值。您可以从sqlfiddle中看到我想要的内容,例如,我在其中使用了来自 IPAddressHistory 和UNION ALL的简单静态日期。谢谢。
初始表:CREATE TABLE IPAddressHistory(
[IPAddressHistoryID] int IDENTITY(1,1) NOT NULL,
[IPAddressID] int NOT NULL,
[DateFrom] datetime,
[DateTo] datetime,
CONSTRAINT [PK_IPAddressHistory] PRIMARY KEY CLUSTERED
(
[IPAddressHistoryID] ASC
)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
CREATE TABLE IPAddressTimeValue(
[IPAddressTimeValueID] int IDENTITY(1,1) NOT NULL,
[IPAddressID] int NOT NULL,
[Time] datetime,
[CCNI] int,
[TRNI] int,
CONSTRAINT [PK_IPAddressTimeValue] PRIMARY KEY CLUSTERED
(
[IPAddressTimeValueID] ASC
)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
初始数据:
结果输出:
最佳答案
您需要的查询是以下查询:
select a.[IPAddressID],
a.[DateFrom],
a.[DateTo],
SUM([CCNI]) [CCNI],
SUM([TRNI]) [TRNI]
from IPAddressHistory a
INNER JOIN IPAddressTimeValue b
ON (a.[IPAddressID] = b.[IPAddressID])
where b.[Time] > a.[DateFrom]
and b.[Time] <= a.[DateTo]
group by a.[IPAddressID], a.[DateFrom], a.[DateTo];
看到它在这里与您自己的选定联合一起工作:http://sqlfiddle.com/#!6/abfe6/5
要根据需要设置日期格式(datefrom和dateto),只需使用一些日期格式功能即可。不要忘记在分组依据的选择字段上使用它。