[我正在尝试计算每天发生的FAILURE
个事件,并将事件存储在MainEventTable
中,其列为EventDateTime
,EventId
和EventStatus
。我正在使用SQL Server Management Studio 2016,但无法识别DATEFROMPARTS
函数。到目前为止,这是我编写的代码:
SELECT
t.EventDate,
SUM(t.EventCount) AS EventCount
FROM (
SELECT
CAST(
(
CAST(
DATEPART(yyyy,s.EventDateTime)
AS VARCHAR(4)
) + '-' +
CAST(
DATEPART(mm,s.EventDateTime)
AS VARCHAR(2)
) + '-' +
CAST(
DATEPART(dd,s.EventDateTime)
AS VARCHAR(2)
)
) AS DATE
) AS EventDate,
Count(s.EventId) AS EventCount
FROM (
SELECT
EventDateTime,
EventId
FROM
MainEventTable WITH(NOLOCK)
WHERE EventDateTime > '2016-12-07 00:00:00'
AND EventStatus = 'FAILURE'
) AS s GROUP BY CAST(
(
CAST(
DATEPART(yyyy,s.EventDateTime)
AS VARCHAR(4)
) + '-' +
CAST(
DATEPART(mm,s.EventDateTime)
AS VARCHAR(2)
) + '-' +
CAST(
DATEPART(dd,s.EventDateTime)
AS VARCHAR(2)
)
) AS VARCHAR(10)
)
) AS t
GROUP BY t.EventDate;
更新:(感谢@wrslphil和@ PM_77-1为我的GROUP BY问题提供帮助)我已经修复了上面的GROUP BY问题,发现这很有效,尽管它很笨重。 @KeithL在下面对其进行了简化...
select CAST(EventDateTime AS DATE),COUNT(*)
FROM MainEventTable
WHERE EventDateTime > '2016-12-07 00:00:00'
AND EventStatus = 'FAILURE'
GROUP BY CAST(EventDateTime AS DATE)
这里没什么可做的,但是,如果您有一个不在按列表分组或在select子句中汇总的项目,则查询绝对不会运行
我认为您可能需要对您的count字段求和...就像这样
SELECT
t.EventDate,
SUM(t.EventCount) as EventCount
FROM (
SELECT
CAST(
(
CAST(
DATEPART(yyyy,s.EventDateTime)
AS VARCHAR(4)
) +
CAST(
DATEPART(mm,s.EventDateTime)
AS VARCHAR(2)
) +
CAST(
DATEPART(dd,s.EventDateTime)
AS VARCHAR(2)
)
) AS DATE
) AS EventDate,
Count(s.EventId) As EventCount
FROM (
SELECT
EventDateTime,
EventId
FROM
MainEventTable WITH(NOLOCK)
WHERE EventDateTime > '2016-12-07 00:00:00'
AND EventStatus = 'FAILURE'
) AS s
) AS t
GROUP BY t.EventDate;
该查询仍然不太可能运行,因为内部查询中存在相同的问题。我可能只是在内部查询中对日期进行转换,然后将其封装在包含count和group by的查询中]
您的子查询具有以下结构:
SELECT field1, COUNT(field2)
FROM theTable
在同一选择中,您使用“原始”字段和聚合(COUNT
)。您没有GROUP BY
子句。
您正在混淆您的SQL引擎,因为无法确定应该选择field1
的值。
如果要计算field2
的非NULL值的记录数,则field1
的非[NULL]值是:SELECT field1, COUNT(field2)
FROM theTable
GROUP BY field1