只选择第一个结果...有更好的方法吗?

时间:2013-01-07 00:55:53

标签: 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 TOP 1 sc.Config_RecID
             FROM SR_Config sc 
            WHERE sc.SR_Service_RecID = s.SR_Service_RecID
       ) 
       OR sc.Config_RecID IS NULL)

有没有更好/更简洁的方法来做到这一点,还是我走在正确的轨道上?

4 个答案:

答案 0 :(得分:2)

您可以将条件移动到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_RecID IS NULL

答案 1 :(得分:0)

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

答案 2 :(得分:0)

这就是你要追求的吗?

;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

答案 3 :(得分:0)

如果你正在使用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