2016-07-13 9 views
0

私は次のようになりますSQLテーブルを持っている:一つのテーブルに2つのクエリの結果

| 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 | 

私は2つの「最新」の値の結果が表示されますクエリを書きたいです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 | 
+1

なぜがないあなただけのUNIONこれら2つのクエリを試してみてください? –

答えて

2

使用して、サブクエリを最大数を見つけること

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

サブクエリは2、最大、明確な数字を取得する:

select FileName, Category, Value, Number 
from Table 
where Number in (SELECT DISTINCT TOP 2 Number FROM Table ORDER BY Number desc); 
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 
    ) 
関連する問題