如何选择背靠背的条目?

时间:2012-09-28 17:15:07

标签: database sql-server-2008 tsql

如何选择在SQL Server 2008数据库中重新创建条目的c_user_id

最好在下面的pras.chla@gmail.com进行3次以上背靠背输入的人员(按c_id descc_id排序是标识列)

c_id    c_user_id             c_entry
1427    xermadr.asdf@me.com   155575
1426    pras.chla@gmail.com   155829
1425    pras.chla@gmail.com   155826
1424    pras.chla@gmail.com   155828
1423    pras.chla@gmail.com   155830
1422    sdfe.qqol@gmail.com   155559 

再次感谢?

2 个答案:

答案 0 :(得分:4)

单程

SELECT DISTINCT c_user_id
FROM   tab t1
       CROSS APPLY (SELECT 1 AS C
                    FROM   (SELECT TOP 2 *
                            FROM   tab t2
                            WHERE  t2.c_id < t1.c_id
                            ORDER  BY t2.c_id DESC) T 
HAVING COUNT(c_user_id) = 2 AND COUNT(DISTINCT c_user_id) = 1 AND MIN(c_user_id) = t1.c_user_id) CA

或另一个

WITH T AS
(
SELECT *,
       ROW_NUMBER() OVER (order by c_id) -
       ROW_NUMBER() OVER (PARTITION BY c_user_id order by c_id) AS Grp
FROM   tab t1
)
SELECT DISTINCT c_user_id
FROM T
GROUP BY c_user_id, Grp
HAVING COUNT(*) >=3

答案 1 :(得分:1)

;WITH someUserTableWithOrderNumber as
(
SELECT ROW_NUMBER ( )  OVER (order by c_id) OrderNumber, 
    c_id, 
    c_user_id, 
    c_entry 
FROM someUserTable
)
SELECT DISTINCT a.c_user_id
FROM someUserTableWithOrderNumber a
JOIN someUserTableWithOrderNumber b on a.OrderNumber = b.OrderNumber + 1 AND a.c_user_id = b.c_user_id 
JOIN someUserTableWithOrderNumber c on b.OrderNumber = c.OrderNumber + 1 AND b.c_user_id = c.c_user_id 
JOIN someUserTableWithOrderNumber d on c.OrderNumber = d.OrderNumber + 1 AND c.c_user_id = d.c_user_id