根据第三列中的日期,从另一个表中的COUNT(*)更新一列

时间:2015-01-14 15:29:15

标签: sql-server

我有一个插入查询,我想重做更新查询 我想要更新的数据库如下:

Date (date, Null)
Hour (int, Null)
No of Alarms Stockholm (int, Null)
No of Alarms Sverige (int, Null)

我的插入查询有效:

INSERT INTO [LABLOG].dbo.[AlarmStatistic] (
    [Date]
    ,[Hour]
    ,[No of Alarms Sverige]
    )
SELECT CAST([Event Date] AS DATE) AS [DATE]
    ,DATEPART(hour, [Event Date]) AS [Hour]
    ,COUNT(*) AS [No of Alarms Sverige]
FROM MYSERVER01.[SESVELOG].[dbo].[STATISTIC]
WHERE [Event Date] >= '2014-07-01'
    AND [Event Date] < '2014-12-01'
    AND [event text] LIKE 'Alarm.BSI Point - Alarm type: On; Alarm status: Normal; Event operator:%RAPID%; Presentation group:%'
GROUP BY CAST([Event Date] AS DATE)
    ,DATEPART(hour, [Event Date])

在阅读了几篇论坛帖子后,我想出了以下内容

UPDATE [LABLOG].[dbo].[AlarmStatistic]
SET [No of Alarms Sverige] = (
        SELECT CAST([Event Date] AS DATE) AS [DATE]
            ,DATEPART(hour, [Event Date]) AS [Hour]
            ,COUNT(*) AS [No of Alarms Sverige]
        FROM MYSERVER01.[SESVELOG].[dbo].[STATISTIC]
        WHERE [Event Date] >= '2014-07-01'
            AND [Event Date] < '2014-12-01'
            AND [event text] LIKE 'Alarm.BSI Point - Alarm type: On; Alarm status: Normal; Event operator:%RAPID%; Presentation group:%'
        GROUP BY CAST([Event Date] AS DATE)
            ,DATEPART(hour, [Event Date])
        )

这不起作用,我得

  

当选择列表中只能指定一个表达式时   子查询不是用EXISTS引入的。

我尝试做的是根据一列中的文本在一台服务器中进行行计数,并在新表中按小时显示行数。

1 个答案:

答案 0 :(得分:1)

您正在使用子查询为[No of Alarms Sverige]分配值。您的子查询应该只返回一个值。但实际上你的子查询返回:

  • 许多行(在一般情况下)
  • 许多专栏(在所有情况下)

我认为以下查询应该有所帮助:

UPDATE [LABLOG].[dbo].[AlarmStatistic]
SET [No of Alarms Sverige] = (
        SELECT COUNT(*) AS [No of Alarms Sverige]
        FROM MYSERVER01.[SESVELOG].[dbo].[STATISTIC]
        WHERE [Event Date] >= '2014-07-01'
            AND [Event Date] < '2014-12-01'
            AND [event text] LIKE 'Alarm.BSI Point - Alarm type: On; Alarm status: Normal; Event operator:%RAPID%; Presentation group:%'
            AND CAST([Event Date] AS DATE) = [Date]
            AND DATEPART(hour, [Event Date]) = [Hour]
        )