我在csv文件中有一些记录通过MS Access数据库加载到MS SQL Server 2016表中。我想在将这些记录插入SQL数据库表之前,使用VBA查询或T-SQL查询(而不是使用记录集的VBA代码)对这些记录进行分组。
示例输入:
ShiftID Name_ID From To Length Size Chargeable**
----------------------------------------------------------------------------
DAY1 CLASSIC_1 0.0 2.8 2.8 NQ2 Yes
DAY1 CLASSIC_1 2.8 5.8 3 NQ2 No
DAY1 CLASSIC_1 5.8 8.0 2.2 NQ2 No
DAY1 CLASSIC_1 8.0 11.1 3.1 NQ2 Yes
DAY1 CLASSIC_1 11.1 14.3 3.2 NQ2 Yes
必需输出:
ShiftID Name_ID From To Length Size Chargeable
----------------------------------------------------------------------
DAY1 CLASSIC_1 0.0 2.8 2.8 NQ2 Yes
DAY1 CLASSIC_1 2.8 8.0 5.2 NQ2 No
DAY1 CLASSIC_1 8.0 14.3 6.3 NQ2 Yes
使用查询:
SELECT ShiftID, Name_ID, Min([From]) AS [From], Max([To]) AS [To], Sum(Length) AS Length,
Size, Chargeable FROM table1
GROUP BY ShiftID, Name_ID, Size, Chargeable
ORDER BY ShiftID, Name_ID, Min([From]), Max([To]), Size, Chargeable;
返回以下记录:
ShiftID Name_ID From To Length Size Chargeable
----------------------------------------------------------------
DAY1 CLASSIC_1 0.0 14.3 9.1 NQ2 Yes
DAY1 CLASSIC_1 2.8 8.0 5.2 NQ2 No
这是我期望的,但不是我需要的。在这个实例中分组并没有给我正确的 To 深度。正确的查询不应返回重叠的间隔。
答案 0 :(得分:1)
这是间隙和岛屿问题。使用以下T-SQL查询:
SELECT ShiftID, Name_ID, [From], [To], Length, Size, Chargeable,
ROW_NUMBER() OVER (PARTITION BY ShiftID, Name_ID, Size
ORDER BY [From]) -
ROW_NUMBER() OVER (PARTITION BY ShiftID, Name_ID, Size, Chargeable
ORDER BY [From]) AS grp
FROM Table1
产生以下输出:
ShiftID Name_ID From To Length Size Chargeable grp
---------------------------------------------------------------
DAY1 CLASSIC_1 3 5 3 NQ2 No 1
DAY1 CLASSIC_1 6 8 2 NQ2 No 1
DAY1 CLASSIC_1 0 2 3 NQ2 Yes 0
DAY1 CLASSIC_1 8 11 3 NQ2 Yes 2
DAY1 CLASSIC_1 11 14 3 NQ2 Yes 2
您现在可以使用grp
合并记录:
SELECT ShiftID, Name_ID, Size,
MIN([From]) AS [From], MAX([To]) AS [To], SUM(Length) AS Length,
Chargeable
FROM (
SELECT ShiftID, Name_ID, [From], [To], Length, Size, Chargeable,
ROW_NUMBER() OVER (PARTITION BY ShiftID, Name_ID, Size
ORDER BY [From]) -
ROW_NUMBER() OVER (PARTITION BY ShiftID, Name_ID, Size, Chargeable
ORDER BY [From]) AS grp
FROM Table1) AS t
GROUP BY ShiftID, Name_ID, Size, Chargeable, grp
答案 1 :(得分:0)
在 Access SQL 中,可以使用子查询来完成:
SELECT
MeasureLevel.ShiftID,
MeasureLevel.Name_ID,
Min(MeasureLevel.From) AS [From],
Max(MeasureLevel.To) AS [To],
Sum(MeasureLevel.Length) AS Length,
MeasureLevel.Size,
MeasureLevel.Chargeable
FROM
(SELECT
Measure.ShiftID,
Measure.Name_ID,
Measure.From,
Measure.To,
Measure.Length,
Measure.Size,
Measure.Chargeable,
(Select
Max(T.From)
From
Measure As T
Where
T.From <= Measure.To And
T.Chargeable = Measure.Chargeable) AS [Level]
FROM
Measure) As MeasureLevel
GROUP BY
MeasureLevel.ShiftID,
MeasureLevel.Name_ID,
MeasureLevel.Level,
MeasureLevel.Size,
MeasureLevel.Chargeable