Sql 仅选择第一个结果。。。有更好的办法吗?
可以有多个Config_RecID,但我只想显示附加到SR_Service_RecID的第一个,如果为NULL,则显示NULLSql 仅选择第一个结果。。。有更好的办法吗?,sql,sql-server,sql-server-2008,tsql,Sql,Sql Server,Sql Server 2008,Tsql,可以有多个Config_RecID,但我只想显示附加到SR_Service_RecID的第一个,如果为NULL,则显示NULL SELECT s.SR_Service_RecID , sc.Config_RecID FROM SR_Service s LEFT JOIN SR_Config sc ON sc.SR_Service_RecID = s.SR_Service_RecID WHERE (sc.Config_RecID =
SELECT s.SR_Service_RecID
, sc.Config_RecID
FROM SR_Service s
LEFT JOIN SR_Config sc
ON sc.SR_Service_RecID = s.SR_Service_RecID
WHERE (sc.Config_RecID =
(
SELECT TOP 1 sc.Config_RecID
FROM SR_Config sc
WHERE sc.SR_Service_RecID = s.SR_Service_RecID
)
OR sc.Config_RecID IS NULL)
是否有更好/更简洁的方法来执行此操作,或者我的思路正确吗?您可以将条件移动到
on
子句中:
SELECT s.SR_Service_RecID
, sc.Config_RecID
FROM SR_Service s
LEFT JOIN SR_Config sc
ON sc.SR_Service_RecID = s.SR_Service_RecID
AND sc.Config_RecID = (
SELECT TOP 1 Config_RecID
FROM SR_Config sc2
WHERE sc2.SR_Service_RecID = s.SR_Service_RecID
)
这样您就不需要额外检查
sc.Config\u RecID是否为NULL
这就是您要找的吗
with Config_RecIDs as (
select SR_Service_RecID
, Config_RecID
, row_number() over (partition by SR_Service_RecID order by Config_RecID) as [rn]
from SR_Config
)
select sc.SR_Service_RecID, c.Config_RecID
from SR_Config as sc
left join Config_RecIDs as s
on s.SR_Service_RecID = c.SR_Service_RecID
and [rn] = 1
;WITH SR_ConfigCTE AS
(
SELECT DISTINCT
SR_Service_RecID
,Config_RecID
FROM SR_Config
)
SELECT s.SR_Service_RecID
,sc.Config_RecID
FROM SR_Service s
LEFT
JOIN SR_ConfigCTE sc ON sc.SR_Service_RecID = s.SR_Service_RecID
如果您使用的是TOP N,则说明您走错了方向。这是不标准和不确定的 相反,你想要第一个。。。某物使用
min()
查找它。连接到该查询或使用相关子查询
我不太理解您的查询,但这里有一个更简单的查询,它给出了每种类型的名字:
select type, usertype, cast(name as varchar(30)) as name
from systypes as t
where exists
( select 1 from systypes
group by type
having min(name) = t.name
and type = t.type
)
order by type
这将产生:
type usertype name
---- -------- ------------------------------
0 0 xml
34 20 image
35 0 ntext
37 0 uniqueidentifier
39 0 nvarchar
45 3 binary
47 1 char
48 5 tinyint
50 16 bit
52 6 smallint
55 24 decimal
56 7 int
58 22 smalldatetime
59 23 real
60 11 money
61 12 datetime
62 8 float
63 0 bigint
122 21 smallmoney
抱歉,标记中的
sql
和tsql
都不表示特定的sql产品,更不用说特定的版本了。请具体说明你在使用什么,也许在你的特殊情况下有一个有效的替代方案。很好。添加到sql-server中。好的。请问是哪个版本?不管是2005年还是2008年,这都很重要。实际上是2008 R2。不,你可能不应该把rn=1
放在WHERE中,那样会使你的外部连接变成内部连接。相反,通过和将其添加到ON子句中。或者,如果你的意思是内部连接,就用内部连接替换左侧,以避免混淆。哎呀!where子句应该是连接条件;代码编辑。绝对是一个更好的方法,谢谢。对我来说效果很好。出于某种原因,仍然显示所有结果,不仅仅是第一个,但谢谢:)