0

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

  • 全球定位系统(gps_id,序列号)
  • 客户(client_id,名称)
  • 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 且 id=112 和 id=113 的序列号。

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

我正在使用 SQL Server 2008。

TIA

4

4 回答 4

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)
于 2012-05-14T13:56:09.273 回答
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
    )
于 2012-05-14T13:52:20.183 回答
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
于 2012-05-14T13:52:37.077 回答
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
于 2012-05-14T13:53:22.693 回答