复杂的T-SQL语句

时间:2014-05-08 19:31:09

标签: sql tsql

我不是最好的SQL程序员,所以我基本上要求某人帮助编写一个可以得到我想要的结果的查询。以下是查询范围的表结构。

CREATE TABLE [dbo].[tblOverNightPermissions] (
[DateAndTime] DATETIME       NULL,
[Address]     NVARCHAR (200) NULL,
[Direction]   NVARCHAR (102) NULL,
[NoOfDays]    INT            NULL,
[UserID]      INT            NOT NULL,
[OverNightID] INT            IDENTITY (1, 1) NOT NULL,
[Exempt]      INT            NULL,
[Beat]        INT            NULL,
CONSTRAINT [PrimaryKey_1fd244dd-bfd8-4998-8439-4d7d7893d387] PRIMARY KEY CLUSTERED ([OverNightID] ASC),
CONSTRAINT [FK_tblOverNightPermissions_0] FOREIGN KEY ([UserID]) REFERENCES [dbo].[tblUsers] ([UserID])

);

CREATE TABLE [dbo].[tblOverNightToVehicles] (
[OverNightID] INT NOT NULL,
[VehicleID]   INT NOT NULL,
[ID]          INT IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PrimaryKey_b433eaad-fb12-493c-9302-3f3bd9bd74e3] PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_tblOverNightToVehicles_0] FOREIGN KEY ([OverNightID]) REFERENCES [dbo].[tblOverNightPermissions] ([OverNightID]) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT [FK_tblOverNightToVehicles_1] FOREIGN KEY ([VehicleID]) REFERENCES [dbo].[tblVehicles] ([VehicleID]) ON DELETE CASCADE ON UPDATE CASCADE

);

我想要做的是从tblOverNightPermissions中选择记录并按月分组。我还想计算当月的记录数,并按照tblOverNightToVehicles中的车辆ID进行分组。目标是进行检查,以确保每个车辆每月ID不超过5次。它有点棘手,因为数据库设计不健全。如您所见,tblOvernightPermissions中的NoOfDays字段使事情变得复杂。用户可以选择连续5天停车,而不是每月总是有一定数量的记录。因此,如果我今天停车并选择5天,我的记录条目将如下所示     DateAndTime = 5/8/2014     地址= x     方向= S.     NoOfDays = 5     UserId = 1     OvernightId = 1     豁免= 0     Beat = 2

这意味着,对于这个月,我将在tblOverNightPermissions中只有一条代表5天停车时间的物理记录。我可以轻松地在表格中创建5条记录,以表示5天的停车时间以及发生问题的地方。在TSQL中编写条件以考虑记录是否有NoOfDays> 1将其添加到当月的物理记录计数中。

以下是填充数据库的脚本

用于填充tblOvernightPermissions https://dl.dropboxusercontent.com/u/62170850/tblOvernightPermissions.txt

的脚本

用于填充tblOvernightToVehicles的脚本 https://dl.dropboxusercontent.com/u/62170850/tblOverNightToVehicles.txt

1 个答案:

答案 0 :(得分:0)

SELECT DATEADD(month, DATEDIFF(month, 0, p.DateAndTime), 0) AS [Month],
     SUM(p.NoOfDays) As Days
FROM tblOverNightPermissions p
INNER JOIN tblOverNightToVehicles v ON p.OverNightID = v.OverNightID
GROUP BY DATEADD(month, DATEDIFF(month, 0, p.DateAndTime), 0), v.VehicleID
HAVING SUM(p.NoOfDays) >= 5