我正在尝试计算在特定时间内针对某些对象记录的记录数。我需要根据针对每个对象记录的记录数返回主键Key
和友好名称FullName
。所有这些都在同一个表EVENTS
中。
Key
或FullName
使用:
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
子句并返回Key
和FullName
列,而无需诉诸INNER JOIN
?
答案 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";