如何在列中重复输入最后插入的行?

时间:2012-05-14 13:39:40

标签: sql sql-server-2008

我的数据库中有4个表,其中包含以下字段:

  • gps(gps_id,serial_number)
  • client(client_id,name)
  • client_gps(client_id,gps_id)
  • person_gps(gps_id,date1,date2)

我需要显示所选客户端的gps设备的所有序列号。 “person_gps”表可以重复“gps_id”记录。

像这样,

gps_id++++date1++++++++date2
===================================
110   ----10/05/99----05/05/05
110   ----03/02/06----NULL
112   ----03/02/04----04/02/04
112   ----05/09/04----06/08/08
113   ----09/09/09----10/03/10

我需要检查每个gps_id的最后一条记录中的“date2”是否为空。所以,在这个例子中,只显示来自gps的serial_number,id = 112,id = 113。

最好的方法是什么?所有这些都应该在存储过程中创建,正如我之前所说的,client_id是一个给定的参数(@client)。

我正在使用SQL Server 2008。

TIA

4 个答案:

答案 0 :(得分:1)

试试这个:

select * from person_gps a
INNER JOIN client_gps b ON a.gps_id = b.gps_id
INNER JOIN gps c on a.gps_id = c.gps_id
WHERE b.client_id = @client_id and NOT EXISTS (select 1 from person_gps
where x a.gps_id = x.gps_id and x.date2 is null)

答案 1 :(得分:0)

也许是这样的:

;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY gps_id 
                     ORDER BY date2 DESC) AS RowNbr,
        person_gps.*
    FROM
        person_gps  
)
SELECT
    *
FROM
    gps
    JOIN CTE
        ON gps.gps_id=CTE.gps_id
        AND CTE.RowNbr=1
WHERE EXISTS
    (
        SELECT
            NULL
        FROM
            client_gps
        WHERE
            client_gps.gps_id=gps.gps_id
            AND client_gps.client_id=2--Limit on some clientid
    )

答案 2 :(得分:0)

SELECT distinct g.serial_number
FROM person_gps pg, client_gps cg, gps g
WHERE cg.client_id = $INPUT
AND pg.gps_id = cg.gps_id
AND g.gps_id = cp.gps_id
AND NOT EXISTS(SELECT 1 
               FROM person_gps
               WHERE gps_id = cg.gps_id
               AND date2 IS NULL)
ORDER BY gps_id

答案 3 :(得分:0)

您可以使用select语句执行此操作。

首先,考虑一下您要选择的行。您可以使用row_number()获取最后一行,然后检查date2是否正确。然后,将它们连接回原始记录以拉出您想要的记录:

select *
from person_gsp pg join
     (select pg.gp_id
      from (select pg.*,
                   row_number() over (partition by gps_id order by date1 desc) as seqnum
            from person_gps pg
           ) pg
      where seqnum = 1 and date2 is not null
     ) ids
     on pg.gp_id ids.gp_id