SQL Server,将2行合并为1并限制行分组

时间:2017-09-07 06:24:03

标签: sql-server tsql grouping

我目前正在进行SQL查询以访问名为" Alarms"的表中的数据。此表的设置格式如下:

AlarmNumber | Time | AlarmState -------------|-------|----------- 1046 | 10:30 | 0 1045 | 10:25 | 1 1044 | 10:24 | 0 1046 | 10:24 | 1 1046 | 10:23 | 0 1046 | 10:22 | 1

我想要实现的是将警报分类为以下格式 目标是显示报警开始时间,报警停止时间和报警活动时间(报警结束时间 - 报警开始时间)

AlarmNumber | AlarmStartTime | AlarmEndTime | AlarmActiveTime -------------|-----------------|--------------|---------------- 1046 | 10:24 | 10:30 | 00:02 1045 | 10:24 | - | 10:24 + Current Time 1044 | Shift Start Time| 10:30 |10:30 - Shift Start Time 1046 | 10:22 | 10:23 | 00:01

我当前的代码如下(注意:_Global_Vars是一个带有时区的表):

SELECT 
    TODATETIMEOFFSET([ALARM_START_TIME],0) AT TIME ZONE (SELECT g.LocalTimeZone FROM _Global_Vars as g) AS [ALARM_START_TIME],
    TODATETIMEOFFSET(ALARM_FINISH_TIME,0) AT TIME ZONE (SELECT g.LocalTimeZone FROM _Global_Vars as g) AS [ALARM_FINISH_TIME],
    DATEDIFF(SS, [ALARM_START_TIME], [ALARM_FINISH_TIME]),
    sub.AlarmNumber
FROM
(
    SELECT 
            (a.[Time]) AS AlarmTime,
            (a.[AlarmNumber]+1) as AlarmNumber,
            (CASE WHEN a.[AlarmState] = 1 THEN a.[Time] END) [ALARM_START_TIME],
            (CASE WHEN a.[AlarmState] = 0 THEN a.[Time] END) [ALARM_FINISH_TIME]
    FROM [Alarms] as a
    WHERE (a.[Time] > DATEADD(mi, - 60.0 * 12, GETUTCDATE()))
)`

目前的问题是,如果我在MAXCASE前面使用GROUP BY AlarmNumber,它会将AlarmNumber的所有值合并为一行,我希望如果警报多次发生,它有多个Alarmnumber实例

我是编写SQL查询的新手,所以任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

我将仅发布部分解决方案(仅包含前三个colmns),因为您没有明确指定最后一列的目标内容。

SELECT t.alarmNumber,
   isnull(MAX(CASE WHEN t.alarmstate = 1 THEN CAST(t.[time] as varchar(20)) END), 'Shift Start Time') AlarmStartTime,
   isnull(MAX(CASE WHEN t.alarmstate = 0 THEN CAST(t.[time] as varchar(20)) END), 'Current Time') AlarmEndTime   
FROM
(
   SELECT *, row_number() over (partition by alarmnumber, alarmstate order by [time]) al_group
   FROM Alarms
) t
GROUP BY t.alarmNumber, t.al_group

demo