1

我有一个名为 vehicle_Summary 的表,数据类似于:

A_Date                         vehicle_Name        Location_Name
2012-02-08 09:36:20.000        AA000AA               Denver
2012-03-08 09:36:20.000        AA000AA               Tokyo
2012-04-08 09:30:50.000        AA000AA               Melbourne
2012-12-08 09:36:20.000        AA000AA               Geneva
2012-22-08 00:00:00.000        AA000AA               NY 

2012-01-08 09:36:20.000        DPT011                Hobart
2012-03-08 09:36:20.000        DPT011                Tasmania
2012-04-08 09:30:50.000        DPT011                Java
2012-12-08 09:36:20.000        DPT011                Manila
2012-22-08 00:00:00.000        DPT011                Singapore

我有 vehicle_Info 表作为

vehicle_Name

DPT011
AA000AA
Z400

所以首先我从vehicle_Info表中搜索所有车辆,当我在vehicle_Summary上查询两个时间间隔时说2012-02-08 04:44:44.444和2012-12-08 09:44:44.444

我期望的是

vehicleName                     start_Point                   end_Point
AA000AA                         Denver                        Geneva
DPT011                          Tasmania                      Manila

我使用 MS Sql server 2k5,我希望它作为查询而不是在 C# 中执行手动逻辑。这可能吗

4

2 回答 2

0

假设 A_Date 为Datetime,您可以使用Between运算符来获得如下结果:-

WHERE A_Date Between '1/20/2009' And '2/21/2009'

或尝试这样:-

WHERE startdate >= startdate AND enddate <=enddate
于 2013-03-16T11:24:21.030 回答
0

你可以这样做:

WITH CTE
AS
(
  SELECT
    vehicle_name,
    MIN(A_Date) AS StartDate,
    MAX(A_Date) AS EndDate
  FROM vehicle_Summary
  WHERE A_Date BETWEEN '2012-08-02 04:44:44.444'
                   AND '2012-08-12 09:44:44.444'
  GROUP BY vehicle_name
)
SELECT 
  c.vehicle_name, 
  s.Location_name AS start_Point, 
  e.Location_name AS end_Point
FROM CTE AS c
INNER JOIN vehicle_summary s  ON s.vehicle_name = c.vehicle_name
                             AND s.A_Date       = c.StartDate 
INNER JOIN vehicle_summary e  ON e.vehicle_name = c.vehicle_name
                             AND e.A_Date       = c.EndDate; 

SQL 小提琴演示

这会给你:

| VEHICLE_NAME | START_POINT | END_POINT |
------------------------------------------
|      AA000AA |      Denver |    Geneva |
|       DPT011 |    Tasmania |    Manila |

更新 1

您还可以JOIN从另一个表中获取车辆名称:

WITH CTE
AS
(
  SELECT
    i.vehicle_id,
    i.vehicle_name,
    MIN(s.A_Date) AS StartDate,
    MAX(s.A_Date) AS EndDate
  FROM vehicle_Summary AS s
  INNER JOIN vehicle_Info AS i ON s.vehicle_id = i.vehicle_id
  WHERE s.A_Date BETWEEN '2012-08-02 04:44:44.444'
                   AND '2012-08-12 09:44:44.444'
  GROUP BY i.vehicle_id,
           i.vehicle_name
)
SELECT 
  c.vehicle_name, 
  s.Location_name AS start_Point, 
  e.Location_name AS end_Point
FROM CTE AS c
INNER JOIN vehicle_summary s  ON s.vehicle_id = c.vehicle_id
                             AND s.A_Date     = c.StartDate
INNER JOIN vehicle_summary e  ON e.A_Date     = c.EndDate
                             AND e.vehicle_id = c.vehicle_id;

更新的 SQL Fiddle 演示

于 2013-03-16T11:40:36.893 回答