DECLARE @Good INT
SELECT @Good = Good
FROM MyTable
WHERE DateDeleted IS NULL
GROUP BY ID
HAVING ID = MIN(ID)
在存储过程中,我想设置变量@Good。我需要的条件是DateDeleted
为空且最小ID
。
示例:
ID Good DateDeleted
-----------------------
1 5 15-12-2013
2 3 null
3 4 null
4 1 null
结果必须为3
我收到的错误信息是:
Msg 8120,Level 16,State 1,Line 4
专栏' MyTable.Good'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
我做错了什么?
有人能帮助我吗?
由于
答案 0 :(得分:3)
DECLARE @Good INT
Select top 1 @Good = Good
From MyTable
Where DateDeleted is null
Order by Id
答案 1 :(得分:0)
如果我理解你是正确的,你希望获得没有删除的最小ID的商品。
我认为它应该是这样的:
DECLARE @Good INT
SELECT @Good = Good
FROM MyTable
WHERE ID = ( SELECT MIN(ID)
FROM MyTable
WHERE DateDeleted IS NULL
)
答案 2 :(得分:0)
使用提供的示例数据,我们可以使用以下SQL获取所需的值:
DECLARE @Good INT
SELECT @Good = Good
FROM MyTable
WHERE Id =
(
SELECT MIN(Id)
FROM MyTable
WHERE DateDeleted IS NULL
)
答案 3 :(得分:0)
解决方案可能是
select @Good = Good
from MyTable
where id = (select MIN(ID) from MyTable WHERE DateDeleted IS NULL)