假设我有一张这样的表:
| FileName | Category | Value | Number |
|:---------:|:--------:|:-----:|:------:|
| TAG File1 | First | 10 | 1 |
| TAG File1 | Second | 8 | 1 |
| TAG File1 | Third | 4 | 1 |
| TAG File2 | First | 13 | 1 |
| TAG File2 | Second | 5 | 1 |
| TAG File2 | Third | 6 | 1 |
| TAG File1 | First | 11 | 2 |
| TAG File1 | Second | 7 | 2 |
| TAG File1 | Third | 5 | 2 |
| TAG File2 | First | 14 | 2 |
| TAG File2 | Second | 6 | 2 |
| TAG File2 | Third | 5 | 2 |
| TAG File1 | First | 10 | 3 |
| TAG File1 | Second | 6 | 3 |
| TAG File1 | Third | 5 | 3 |
| TAG File2 | First | 12 | 3 |
| TAG File2 | Second | 7 | 3 |
| TAG File2 | Third | 4 | 3 |
我想要一个可以从数据中得到这个的查询:
| FileName | Category | Value | Number |
|:---------:|:--------:|:-----:|:------:|
| TAG File1 | First | 10 | 3 |
| TAG File1 | Second | 6 | 3 |
| TAG File1 | Third | 5 | 3 |
| TAG File2 | First | 12 | 3 |
| TAG File2 | Second | 7 | 3 |
| TAG File2 | Third | 4 | 3 |
我可以通过
轻松完成此操作SELECT *
FROM Table
WHERE Number = 3;
但是我们可以说这个表不断记录数据,而Number
列正在跟踪每次再次收集数据的时间。但我希望能够通过一个查询来提取数据,这个查询总是会给我“最新”的数字。换句话说,Number
列中的最大值。但是,我也不希望数字列实际显示在结果中。所以它看起来像这样:
| FileName | Category | Value |
|:---------:|:--------:|:-----:|
| TAG File1 | First | 10 |
| TAG File1 | Second | 6 |
| TAG File1 | Third | 5 |
| TAG File2 | First | 12 |
| TAG File2 | Second | 7 |
| TAG File2 | Third | 4 |
在我脑海中,我可以看到这样的查询:
SELECT FileName, Category, Value
FROM Table
WHERE Number = "Maximum";
但当然这根本不起作用......
这可能吗?
编辑:我写的这个问题没有解决可能是最大的问题。我正在使用sqlQuery
函数在R中编写这些查询,我从来没有能够使子查询起作用。换句话说,我不能只写:
SELECT FileName, Category, Value
FROM Table
WHERE (select Max(Number) from Table);
答案 0 :(得分:2)
您可以使用CTE
使其正常工作。请参阅以下代码:
;WITH TempHolder AS
(
SELECT MAX(Number) MaxNumber FROM Table
)
SELECT FileName, Category, Value FROM Table t1
JOIN TempHolder th ON t1.Number = th.MaxNumber
答案 1 :(得分:0)
with most_recent as (
SELECT t.FileName, t.Category, MAX(t.Number) as Number
FROM Table t
GROUP BY t.FileName, t.Category
)
select t.FileName, t.Category, t.value
FROM Table t
INNER JOIN most_recent mr
ON (mr.FileName = t.FileName and mr.Category = t.Category and mr.Number = t.Number)
答案 2 :(得分:0)
你可以这样做:
SELECT TOP 1 WITH TIES
FileName,
Category,
Value
FROM
Table
ORDER BY
Number DESC