如何在连接查询中选择不同的列

时间:2013-08-30 11:17:05

标签: sql sql-server

我想使用两个表的连接从数据表中选择不同的GTIM列值。     这是我的询问..

SELECT TOP (9) Tracking.LAMI,
  Tracking.LGMI,
  Tracking.SPED,
  Tracking.BAT_ADC,
  Tracking.GTIM,
  Tracking.MAIN_BACKUP,
  Tracking.PULSE_CTR,
  Tracking.NOST,
  Tracking.IGST,
  Tracking.COND_INPUTS,
  Tracking.FUEL_ADC,
  Tracking.M,
  Vehicles_Device_Rel.VehicalNumber
FROM Tracking
INNER JOIN Vehicles_Device_Rel
  ON Tracking.M = Vehicles_Device_Rel.Device_ID
WHERE (Vehicles_Device_Rel.VehicalNumber = 'test')
ORDER BY GTIM DESC

示例输出:

12.988000 77.68367400 6 543 2013-08-30 17:26:00.000 1 0.00 10 1 99 10 10 test    
12.918800 77.65367400 6 543 2013-08-30 17:25:00.000 1 0.00 10 1 99 10 10 test 
12.968800 77.65367400 4 543 2013-08-30 17:25:00.000 1 0.00 10 1 99 10 10 test    
12.891880 77.65367400 6 543 2013-08-30 17:24:00.000 1 0.00 10 1 99 10 10 test

3 个答案:

答案 0 :(得分:0)

这会选择不同的值。这是你想要的吗?

SELECT distinct Tracking.GTIM
FROM Tracking
INNER JOIN Vehicles_Device_Rel
  ON Tracking.M = Vehicles_Device_Rel.Device_ID
WHERE (Vehicles_Device_Rel.VehicalNumber = 'test')

答案 1 :(得分:0)

您可以使用SELECT DISTINCT GTIM FROM TRACKING加入当前查询。

这样的事情:

SELECT TOP (9) Tracking.LAMI,
  Tracking.LGMI,
  Tracking.SPED,
  Tracking.BAT_ADC,
  Tracking.GTIM,
  Tracking.MAIN_BACKUP,
  Tracking.PULSE_CTR,
  Tracking.NOST,
  Tracking.IGST,
  Tracking.COND_INPUTS,
  Tracking.FUEL_ADC,
  Tracking.M,
  Vehicles_Device_Rel.VehicalNumber
FROM Tracking
INNER JOIN Vehicles_Device_Rel
  ON Tracking.M = Vehicles_Device_Rel.Device_ID
INNER JOIN (SELECT DISTINCT GTIM FROM TRACKING) T ON T.GTIM = Tracking.GTIM
WHERE (Vehicles_Device_Rel.VehicalNumber = 'test')
ORDER BY Tracking.GTIM DESC

我认为这是您要查找的查询。

答案 2 :(得分:0)

; WITH cte AS
  ( SELECT 
      Tracking.LAMI,
      Tracking.LGMI,
      Tracking.SPED,
      Tracking.BAT_ADC,
      Tracking.GTIM,
      Tracking.MAIN_BACKUP,
      Tracking.PULSE_CTR,
      Tracking.NOST,
      Tracking.IGST,
      Tracking.COND_INPUTS,
      Tracking.FUEL_ADC,
      Tracking.M,
      Vehicles_Device_Rel.VehicalNumber,
      RowN = ROW_NUMBER() OVER (PARTITION BY Tracking.GTIM 
                                ORDER BY SomeColumn)            -- your choice
    FROM Tracking
    INNER JOIN Vehicles_Device_Rel
      ON Tracking.M = Vehicles_Device_Rel.Device_ID
    WHERE (Vehicles_Device_Rel.VehicalNumber = 'test')
  )
SELECT TOP (9) *
FROM cte
WHERE RowN = 1
ORDER BY GTIM DESC ;