把逻辑放在SELECT中

时间:2015-03-20 09:12:24

标签: sql sql-server-2008

我有一个查询,我从汽车和加油卡收集数据。一般来说,我所做的是在给定的时间范围内,我收集所有汽车及其里程数。所以可能的结果是:

enter image description here

我现在需要做的是检查日期1的里程数是否小于日期2的里程数。根据我的情况,我会在新列中添加“是”或“否”,以跟踪数据是否有效。

这在SQL中可行吗?

编辑:

这是SELECT代码。上面有更多的代码来创建像'CarList'这样的东西,但我不认为那些很重要。

    SELECT 
    CAR.beginmonth
,   CAR.endmonth
--, CAR.X_AXIS
--,   CAR.X_AXIS_2
,   CAR.CarID 
--, AL.AllocationName
--, CAR.AllocationID
--, CAR.StartDate
--, CAR.FinalEndDate
,   (CASE   WHEN CAR.CarID IS NULL 
            THEN 'N'
            ELSE 'Y'
            END ) as ValidData
,   CAR.Nature
,   CAR.BuiltYear
,   CAR.Co2Emission
,   fuelcardrefill.Kilometer
,   fuelcardrefill.FK_FuelType
,   fuelcardrefill.Date

From    CarList AS CAR inner join
        dbo.eMK_CarFuelCard as carfuelcard On CAR.CarID = carfuelcard.CarID inner join
        dbo.eMK_FuelCard as fuelcard on carfuelcard.FuelCardID = fuelcard.ID inner join 
        dbo.eMK_FuelCard_Refill as fuelcardrefill on fuelcard.ID = fuelcardrefill.FK_FuelCard

        LEFT Join 
        AllocationList as AL on CAR.AllocationID = AL.CostAllocationID

Where (CAR.AllocationID = @AllocationID) OR (@AllocationID IS NULL) AND 
      (fuelcardrefill.Date > beginmonth and fuelcardrefill.Date < endmonth)

UNION

SELECT 
    AL.MonthDate as beginmonth
,   AL.endmonth
--, AL.X_AXIS
--,   AL.X_AXIS_2
,   NULL as CarID 
--, AL.AllocationName
--, AL.CostAllocationID
--, NULL as StartDate
--, NULL
,   'N' as ValidData
,   NULL
,   NULL
,   NULL
,   NULL
,   NULL
,   NULL

From    AllocationCrossList as AL
--Where (ISNULL(AL.CostAllocationID,NULL) = ISNULL(@AllocationID,NULL) ) 
order by beginmonth, CarID, Date

1 个答案:

答案 0 :(得分:0)

很难给出完整的答案,因为您还没有明确说明您的数据模型是什么以及里程来自哪里。所以,我会尝试在这里给出简化的答案。

假设您有包含所提供样本数据的表CarData:

enter image description here

然后你可以这样写:

SELECT
    CD1.*,
    --data is not valid if we can find older record with greater mileage on the same car
    CASE WHEN EXISTS(
        SELECT 
            *
        FROM 
            CarData AS CD2
        WHERE
            CD2.CarId = CD1.CarId AND -- same car
            CD2.[Date] < CD1.[Date] -- older date
            CD2.Mileage > CD1.Mileage -- greater mileage
    ) 
    THEN 'N' 
    ELSE 'Y' 
    END AS IsValidMileage
FROM
    CarData AS CD1

您可以使用评论中提到的自联接做同样的事情,但我认为这种方法更具可读性。