Dyl*_*con 6 sql-server sql-server-2012
我有下表:
----------------------------------------------
| ID | interestingData | timestamp |
----------------------------------------------
| 1 | 400 | 2016-01-23 17:01:00 |
----------------------------------------------
| 1 | 400 | 2016-01-24 17:01:00 |
----------------------------------------------
| 1 | 350 | 2016-01-25 17:01:00 |
----------------------------------------------
| 2 | 23 | 2016-01-23 17:01:00 |
----------------------------------------------
| 2 | 34 | 2016-01-24 17:01:00 |
----------------------------------------------
| 2 | 12 | 2016-01-25 17:01:00 |
----------------------------------------------
Run Code Online (Sandbox Code Playgroud)
我们的PK在哪里(ID, timestamp)。我正在尝试确定一个查询,该查询将为我提供唯一 ID 和最新的有趣数据,其中有趣数据超过了阈值。当然,这将通过以下方式完成:
SELECT DISTINCT ID
FROM table
WHERE interestingData > threshold
ORDER BY timestamp DESC;
Run Code Online (Sandbox Code Playgroud)
但是,我想要有趣数据超过阈值的每次出现次数。我的结果表最好看起来像
------------------------------------------------------
| ID | interestingData | timestamp | count |
------------------------------------------------------
| 1 | 350 | 2016-01-25 17:01:00 | 3 |
------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
我的阈值是 300。我知道如果你想将不同的东西与一组数据配对,那么左外连接将是有序的,但我不完全确定如何去做。这是迄今为止我能想到的最接近的。
SELECT DISTINCT ID
FROM table t1
LEFT OUTER JOIN table t2 ON t1.ID = t2.table.ID
WHERE interestingData > 300
ORDER BY timestamp DESC
Run Code Online (Sandbox Code Playgroud)
这为我提供了不同的 ID,并根据需要将它们与其余数据配对,但没有规定获取结果的其他部分,更不用说计数了。
如果您想要interestingData和timestamp来自同一行(超过阈值的最新行),并且如果您想包括超过阈值的所有行,即使该 ID 的某些行不满足阈值,则:
;WITH x AS
(
SELECT ID, interestingData, [timestamp],
[count] = COUNT(1) OVER (PARTITION BY ID),
rn = ROW_NUMBER()
OVER (PARTITION BY ID ORDER BY [timestamp] DESC)
FROM dbo.tablename
WHERE interestingData > 300
)
SELECT ID, interestingData, [timestamp], [count]
FROM x
WHERE rn = 1;
Run Code Online (Sandbox Code Playgroud)
此外,尽量避免使用数据类型和/或保留关键字作为列名。timestamp不是一个很好的选择,因为(a)它不是很有意义并且(b)它在很多情况下都需要方括号。