SQL中的高效计数和分组:1999

时间:2017-06-26 15:23:00

标签: sql

我正在尝试计算在特定时间内针对某些对象记录的记录数。我需要根据针对每个对象记录的记录数返回主键Key和友好名称FullName。所有这些都在同一个表EVENTS中。

KeyFullName使用:

轻松完成此操作
SELECT FullName, COUNT(*) AS "RecordNum"
FROM TableA
WHERE RecordTime BETWEEN TIMESTAMP Start AND TIMESTAMP Finish
GROUP BY FullName

如果我想使用

返回两者
SELECT FullName, Key, COUNT(*) AS "RecordNum"
FROM TableA
WHERE RecordTime BETWEEN TIMESTAMP Start AND TIMESTAMP Finish
GROUP BY FullName

我收到错误

  

选择元素键无效,因为列引用未包含在摘要函数或GROUP BY子句中。

我可以将顶部表格创建为TableB,然后将其加入TableA

SELECT TableA.FullName, TableA.Key, TableB."RecordNum"
FROM TableA INNER JOIN
    (SELECT Key, COUNT(*) AS "RecordNum"
    FROM TableA
    WHERE RecordTime BETWEEN TIMESTAMP Start AND TIMESTAMP Finish
    GROUP BY FullName) As TableB On TableA.Key = TableB.Key
ORDER BY TableB.RecordNum DESC

这似乎是一个很长的关于进行查询的方式,因为它们都包含在同一个表中。我是否可以使用GROUP BY子句并返回KeyFullName列,而无需诉诸INNER JOIN

1 个答案:

答案 0 :(得分:0)

只需使用窗口功能:

SELECT a.*, COUNT(*) OVER (PARTITION BY a.FullName) AS "RecordNum"
FROMT TableA a
WHERE a.RecordTime BETWEEN TIMESTAMP a.Start AND TIMESTAMP a.Finish
ORDER BY "RecordNum";