我在SQL Server 2012中工作。我有一个包含2列以下的表
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}

<table style="width:100%">
<tr>
<th>ID</th>
<th>Version</th>
</tr>
<tr>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
</tr>
</table>
&#13;
我想只获得拥有2个以上版本的id而不包含最新的2个版本(意味着Id 1有4个版本,其中我只需要提取最新的2个版本(3,2))。
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
&#13;
<table style="width:100%">
<tr>
<th>Id</th>
<th>Version</th>
</tr>
<tr>
<td>1</td>
<td>0</td>
</tr>
<tr><td>1</td>
<td>1</td></tr>
<tr><td>2</td>
<td>0</td></tr>
</table>
&#13;
如何编写查询?我已经尝试了以下查询select * from bitest,其中版本不在
(
从bitest中选择版本(其中的版本)
SELECT Max(版本)
来自bitest
GROUP BY id
HAVING Max(版本)&gt; = 2
))
并且身份证明
(
从bitest中选择不同的id,其中的版本是(
SELECT Max(版本)
来自bitest
GROUP BY id
HAVING Max(版本)&gt; = 2
))请更正查询以获得所需的结果
答案 0 :(得分:0)
要仅获取包含2个以上版本的ID,请尝试以下操作:
SELECT id,COUNT(version) FROM tt GROUP BY id HAVING COUNT(version)>2
答案 1 :(得分:0)
DECLARE @DataSource TABLE
(
[ID] TINYINT
,[Version] TINYINT
);
INSERT INTO @DataSource ([ID], [Version])
VALUES (1,0)
,(1,1)
,(1,2)
,(1,3)
,(2,0)
,(2,1)
,(2,2)
,(3,0)
,(3,1);
SELECT [ID]
,MIN([Version]) AS [Version]
FROM @DataSource
GROUP BY [ID]
HAVING COUNT([Version]) > 2;
答案 2 :(得分:0)
如果我理解正确,你正在寻找: -
Set Nocount On;
Declare @test Table
(
Id Int
,Version Int
)
Insert Into @test(Id,Version) Values
(1,0)
,(1,1)
,(1,2)
,(1,3)
,(2,0)
,(2,1)
,(2,2)
,(3,0)
,(3,1)
Select *
From @test As t
Where t.Version Not In ( Select Top 2
t.Version
From @test As t
Order By t.Version Desc
)
---- Ids which having more than 2 versions BUT NOT latest 2 Versions.
Select t.Id
From @test As t
Where t.Version Not In ( Select Top 2
t.Version
From @test As t
Order By t.Version Desc
)
Group By t.Id
Having Count(t.Version) > 2