2010-06-24 182 views
4

我需要一点帮助来编写查询。我有这个数据...Sql联合查询帮助

vDir iNumber 
North 19 
North 27 
North 29 
North 31 
South 46 
South 49 
South 51 
South 61 

我需要查询数据,并输出这样的事情

vDir iLowNumber iHiNumber 
North 19   27 
North 27   29 
North 29   31 
South 46   49 
South 49   51 
South 51   61 

这里的想法是选择方向,LowNum然后nextNumber。当方向改变时重新开始。 (这就是为什么我认为我需要一个联盟,也许是北方,然后是南方联盟)。请注意,由于没有更高的数字,因此每个方向上的最高数字不会创建记录。第一组有8条记录,查询结果只有6条。我怎样才能创建一个查询来做到这一点?任何帮助表示赞赏。这也是2008 SQL数据库,所以我可以使用2008 TSQL。我需要光标吗?或许更好的使用c#和Linq的解决方案?我真的很好奇如何在SQL中做到这一点。多谢你们!

干杯, 〜CK在圣地亚哥

+0

我不认为联盟在这里是必要的。我将它从标签列表中删除,然后添加sql-server,以便获得更多的目光。 – 2010-06-24 15:50:17

+0

看起来像http://ask.sqlservercentral.com上的问题之一 - 不确定是否可以立即找到合适的问题,但如果您在那里问问题,您可能会得到一个快速答案! – 2010-06-24 15:53:19

+0

问题:iLowNumber/iHiNumbers只会增加吗?你有没有在序列中获得vDir的单个条目? – 2010-06-24 15:54:29

回答

2

另一种可能的解决方案:

SELECT 
    T1.vDir, 
    T1.iNumber AS iLowNumber, 
    T2.iNumber AS iHiNumber 
FROM 
    My_Table T1 
INNER JOIN My_Table T2 ON 
    T2.vDir = T1.vDir AND 
    T2.iNumber > T1.iNumber 
LEFT OUTER JOIN My_Table T3 ON 
    T3.vDir = T1.vDir AND 
    T3.iNumber > T1.iNumber AND 
    T3.iNumber < T2.iNumber 
WHERE 
    T3.vDir IS NULL -- If this is NULL it means that no rows exist between T1 and T2 
+0

子查询解决方案更符合我绘制问题的方式,但这是一个非常优雅的解决方案。对于数据集越来越大,它也应该很快。 – Bill 2010-06-24 16:11:46

+0

非常感谢。这是一个非常干净清晰的解决方案!生成正确的输出。做得好! – Hcabnettek 2010-06-24 16:24:14

1
select a.vDir, 
      a.iNumber as iLowNumber, 
      b.iNumber as iHiNumber 
     from TheTable a 
inner join TheTable b on a.vDir = b.vDir 
        and a.iNumber < b.iNumber 
        and not exists(select 1 
            from TheTable c 
            where a.vDir = b.vDir 
            and a.iNumber < c.iNumber 
            and c.iNumber < b.iNumber) 

有趣的是有3个不同的答案,到目前为止,各有不同的性能特点。

0

这一定要做好

select * from(
select direction,inumber as low, 
(select top(1) inumber from cte as b where b.direction=a.direction 
and b.INumber>a.inumber) as high 
from cte as a 
) as x where high is not null 
0

在我看来最自然的解决方案是:

select t1.vdir, t1.inumber as lownumber, min(t2.inumber) as highnumber 
from mytable t1 
join mytable t2 on t2.vdir=t1.vdir 
    and t2.inumber>t1.inumber 
group by t1.vdir, t1.inumber 
order by t1.vdir, t1.inumber 

如何的这个性能比较我还没有研究其他解决方案。