我想从SQL表中连续获得2行。 存储UNIX日期戳的列之一和2行之间的差别仅为此值。
例如:
id_int dt_int
1. row 8211721 509794233
2. row 8211722 509794233
我只需要那些dt_int相同(编辑过)
的行答案 0 :(得分:0)
你想要显示两条线吗?
解决方案可能是这样的:
with foo as
(
select
*
from (values (8211721),(8211722),(8211728),(8211740),(8211741)) a(id_int)
)
select
id_int
from
(
select
id_int
,id_int-isnull(lag(id_int,1) over (order by id_int) ,id_int-6) prev
,isnull(lead(id_int,1) over (order by id_int) ,id_int+6)-id_int nxt
from foo
) a
where prev<=5 or nxt<=5
我们使用超前和滞后来查找行之间的差异,并保留行之前或之后行的小于或等于5的行。
如果您使用2008r2,则无法使用滞后和潜在客户。您可以使用rownumber代替:
with foo as
(
select
*
from (values (8211721),(8211722),(8211728),(8211740),(8211741)) a(id_int)
)
, rownums as
(
select
id_int
,row_number() over (order by id_int) rn
from foo
)
select
id_int
from
(
select
cur.id_int
,cur.id_int-prev.id_int prev
,nxt.id_int-cur.id_int nxt
from rownums cur
left join rownums prev
on cur.rn-1=prev.rn
left join rownums nxt
on cur.rn+1=nxt.rn
) a
where isnull(prev,6)<=5 or isnull(nxt,6)<=5
答案 1 :(得分:0)
你可以尝试一下。此版本适用于SQL Server 2000及更高版本。今天我不想写更新的SQL Server。
declare @t table (id_int int, dt_int int)
INSERT @T SELECT 8211721 , 509794233
INSERT @T SELECT 8211722 , 509794233
INSERT @T SELECT 8211723 , 509794235
INSERT @T SELECT 8211724 , 509794236
INSERT @T SELECT 8211729 , 509794237
INSERT @T SELECT 8211731 , 509794238
;with cte_t as
(SELECT
ROW_NUMBER() OVER (ORDER BY id_int) id
,id_int
,dt_int
FROM @t),
cte_diff as
( SELECT
id_int
,dt_int
,(SELECT TOP 1 dt_int FROM cte_t b WHERE a.id < b.id) dt_int1
,dt_int - (SELECT TOP 1 dt_int FROM cte_t b WHERE a.id < b.id) Difference
FROM cte_t a
)
SELECT DISTINCT id_int , dt_int FROM @t a
WHERE
EXISTS(SELECT 1 FROM cte_diff b where b.Difference =0 and a.dt_int = b.dt_int)
答案 2 :(得分:0)
假设:
lead()
分析功能可用。 lead(ID_int) over(partition by SomeKeysuchasOrderNumber order by ID_int asc)
进行分区,以便订单和日期不会混合在一起。
WITH CTE AS (
SELECT A.*
, lead(ID_int) over ([missing partition info] ORDER BY id_Int asc) - id_int as ID_INT_DIFF
FROM Table A)
SELECT *
FROM CTE
WHERE ID_INT_DIFF < 5;