将两个查询的结果合并到一个表中

时间:2016-07-13 19:14:27

标签: sql sql-server aggregate-functions

我有一个看起来像这样的SQL表:

|  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 |
| TAG File1 | First    |    11 |      4 |
| TAG File1 | Second   |     8 |      4 |
| TAG File1 | Third    |     5 |      4 |
| TAG File2 | First    |    13 |      4 |
| TAG File2 | Second   |     5 |      4 |
| TAG File2 | Third    |     5 |      4 |

我想编写一个查询,只显示Number列中两个“最新”值的结果。数字列是计数值。每次使用一组新数据更新此表时,该组数据的Number列中的值与最大值相差+1。最终,我想要一个可以完成此查询的查询。

select FileName, Category, Value, (select max(Number) from Table) as Number
from Table;

同时在表格中也有这些结果:

select FileName, Category, Value, (select max(Number)-1 from Table) as Number
from Table;

结果应如下所示:

|  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 |
| TAG File1 | First    |    11 |      4 |
| TAG File1 | Second   |     8 |      4 |
| TAG File1 | Third    |     5 |      4 |
| TAG File2 | First    |    13 |      4 |
| TAG File2 | Second   |     5 |      4 |
| TAG File2 | Third    |     5 |      4 |

3 个答案:

答案 0 :(得分:2)

使用子查询查找最大数量

SELECT * FROM table WHERE number >= (SELECT MAX(number) FROM table) - 1

答案 1 :(得分:0)

您可以使用子查询来获取2个最大的不同数字:

select FileName, Category, Value, Number
from   Table
where  Number in (SELECT DISTINCT TOP 2 Number FROM Table ORDER BY Number desc);

答案 2 :(得分:0)

试试这个

SELECT
    FileName, 
    Category, 
    Value, 
    Number
FROM   
    TABLE T
WHERE
    T.Number IN 
    ( 
        SELECT DISTINCT TOP 2 Number 
        FROM Table IT
        WHERE
            IT.FileName  = T.FileName AND
            IT.Category = T.Category    
        ORDER BY IT.Number DESC
    )