从ms sql中的第一个数据中减去最后一个数据,但每天都这样做

时间:2015-03-25 06:16:15

标签: sql-server

我有一个MS sql查询,我在其中计算了我的汽车总公里数。为此,我创建了一个查询,它获取最后一个数据并从第一个数据中减去它。我可以每天实现这一目标,但我现在需要的是每天都有,但是在日期范围内。这是我的1个日期过滤器的代码。

SELECT TOP 1 
(
    (
        (SELECT TOP 1 cast(kmrun as decimal(7,2)) as totkm 
            from [MARK_PASSIVE].[dbo].tblkmrun2 
                where PHILTIME BETWEEN '2015-03-02 00:00:00' AND '2015-03-02 23:59:00' 
                    AND PLATENO = 'UUM572' ORDER BY PHILTIME DESC) 
                    - 
        (SELECT TOP 1 cast(kmrun as decimal(7,2)) as totkm 
            from [MARK_PASSIVE].[dbo].tblkmrun2 
                where PHILTIME BETWEEN '2015-03-02 00:00:00' AND '2015-03-02 23:59:00' 
                    AND PLATENO = 'UUM572' ORDER BY PHILTIME ASC)
    )
) as finkm , 
(CONVERT(char(10), PHILTIME, 126)) as NEWDATE 
from [MARK_PASSIVE].[dbo].tblkmrun2 
where PHILTIME BETWEEN '2015-03-02 00:00:00' AND '2015-03-02 23:59:00'

现在我的代码是日期范围和结果。结果显示相同,但​​它必须不一样,因为我每天运行的总公里数不是整个日期范围

SELECT DISTINCT (CONVERT(char(10), PHILTIME, 126)), 
( 
    (
        (
            SELECT TOP 1 cast(kmrun as decimal(7,2)) as totkm 
                from [MARK_PASSIVE].[dbo].tblkmrun2 
                    where PHILTIME BETWEEN '2015-03-01 00:00:00' AND '2015-03-06 23:59:00' 
                        AND PLATENO = 'UUM572' group by kmrun ORDER BY PHILTIME DESC
        ) - 
        (
            SELECT TOP 1 cast(kmrun as decimal(7,2)) as totkm 
                from [MARK_PASSIVE].[dbo].tblkmrun2 
                    where PHILTIME BETWEEN '2015-03-01 00:00:00' AND '2015-03-06 23:59:00' 
                        AND PLATENO = 'UUM572' ORDER BY PHILTIME ASC
        )
    )
) as finkm , 
(CONVERT(char(10), PHILTIME, 126)) as NEWDATE 
    from [MARK_PASSIVE].[dbo].tblkmrun2 
        where PHILTIME BETWEEN '2015-03-01 00:00:00' AND '2015-03-06 23:59:00'
            ORDER BY NEWDATE DESC

这是日期范围的结果

enter image description here

这是预期的结果

enter image description here

我对日期范围的查询问题是它正在计算整个日期范围,从1获取第一个数据,从6获取最后一个数据。

请帮我重新配置日期范围的SQL查询。

由于

March1的数据

enter image description here

Mar2数据

enter image description here

Mar3的数据

enter image description here

3月4日的数据

enter image description here

3月5日的数据

enter image description here

3月6日的数据

enter image description here

结果可能会有所不同,因为我仅将数据限制为5。

1 个答案:

答案 0 :(得分:1)

试试这个:

DECLARE @startDate  DATE = '20150301'
DECLARE @endDate    DATE = '20150306'

;WITH Cte AS(
    SELECT *,
        FirstPhilTime = ROW_NUMBER() OVER(PARTITION BY CAST(PhilTime AS DATE) ORDER BY PhilTime ASC),
        LastPhilTime = ROW_NUMBER() OVER(PARTITION BY CAST(PhilTime AS DATE) ORDER BY PhilTime DESC)
    FROM tblkmrun2
)
SELECT
    CAST(PhilTime AS DATE),
    FinKm = MAX(CASE WHEN LastPhilTime = 1 THEN KmRun END) - MAX(CASE WHEN FirstPhilTime = 1 THEN KmRun END)
FROM cte
WHERE
    PhilTime >= @STARTDATE
    AND PhilTime < DATEADD(DAY, 1, @ENDDATE)
GROUP BY CAST(PhilTime AS DATE)