Sql server 将在不显示列的情况下提取列的最大值的查询
假设我有一张这样的桌子:Sql server 将在不显示列的情况下提取列的最大值的查询,sql-server,r,Sql Server,R,假设我有一张这样的桌子: | FileName | Category | Value | Number | |:---------:|:--------:|:-----:|:------:| | TAG File1 | First | 10 | 1 | | TAG File1 | Second | 8 | 1 | | TAG File1 | Third | 4 | 1 | | TAG File2 | First |
| 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;
但假设此表持续记录数据,数字列跟踪每次再次收集数据的时间。但我希望能够通过一个查询获取数据,该查询将始终提供最新的数字。换句话说,数字列中的最大值。但是,我也不希望数字列实际显示在结果中。所以看起来是这样的:
| 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";
在我的脑海中,我可以看到这样的疑问:
| 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);
最近的
选择t.FileName、t.Category、MAXt.Number作为编号
来自表t
按t.FileName、t.Category分组
选择t.FileName、t.Category、t.value
来自表t
内部连接最近的mr
在mr.FileName=t.FileName和mr.Category=t.Category和mr.Number=t.Number上
您可以使用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
您可以这样做:
SELECT TOP 1 WITH TIES
FileName,
Category,
Value
FROM
Table
ORDER BY
Number DESC
是什么阻止您编写简单的子查询?其中Number=从中选择MAXNumberTable@techspider啊,这实际上是一个很好的问题,我应该在原始答案中提出。我没有想到这一点,因为我已经习惯了不能在这个领域进行子查询。请参阅我将要进行的编辑。根据您的标记,我不确定您使用的是哪个SQL Server版本!!我希望CTE能为您服务: