简体   繁体   English

给定时间段内每天的2个最大日期之间的日期差异

[英]Date diff between 2 max dates, per day over a given time period

I'm trying to write a sql query to return the difference between a closing time and the final sale of the day for a given location, per day. 我正在尝试编写一个sql查询,以返回指定时间每天的关闭时间与一天的最终销售之间的差额。

The DB schema is something like: 数据库模式类似于:

Store_Closing_table(storeCloseTime, storeId) store_sale_table(saleTime, storeID) Store_Closing_table(storeCloseTime,storeId)store_sale_table(saleTime,storeID)

I've written the following(pseudo code): 我写了以下(伪代码):

select max(storeCloseTime), 
max(saleTime), datediff(mi, max(saletime), 
max(storeCloseTime)) as timeDifference, storeID 
from store_closing_table a
inner join store_sale_table b
on a.storeid = b.storeid
group by storeid, convert(date, saletime), convert(date, storeCloseTime)

Which returns the time difference between the final sale of the day and the store's closing time, but only for the most recent date(ie the max date). 它返回当天的最终销售与商店关闭时间之间的时间差,但仅针对最近的日期(即最大日期)。

I'm not sure how to get the max sale date per day and the max store closing time per day(there are situations where the store 'closes' more than once in a day) and then get the datediff between the two. 我不确定如何获取每天的最大销售日期和每天的最大关闭时间(在某些情况下,商店每天“关闭”多次),然后获取两者之间的datediff。

Any suggestions would be appreciated. 任何建议,将不胜感激。

EDIT: I modified the query to include group by clauses, which gets me closer, but I'm getting the difference between each store sale and each store closing time. 编辑:我修改了查询以包括group by子句,这使我更加接近,但是我得到了每个商店销售和每个商店关闭时间之间的差异。

Ie store has 3 sales over 3 days. 即商店在3天内有3笔交易。 I'm getting close 1 - sale a, close 1 - sale b, close 1 - sale c, close 2 - sale a, close 2 -sale b, close 2 - sale c, close 3 - sale a, close 3 - sale b, close 3 - sale c. 我要接近1-出售a,接近1-出售b,接近1-出售c,接近2-出售a,接近2-出售b,接近2-出售c,接近3-出售a,接近3-出售b,关闭3-出售c。

Any ideas? 有任何想法吗?

please try this. 请尝试这个。

WITH cte
AS ( 
       select StoreID,
              CONVERT(DATE, storeCloseTime) AS [Date], 
              max(storeCloseTime) as storeCloseTime,
              max(saleTime) as SaleTime,
         FROM Store_closing_table AS a
         JOIN Store_sale_table AS b ON a.storeid = b.storeid
        GROUP BY StoreID, CONVERT(DATE, storeCloseTime)
    )
       SELECT StoreID, [Date], StoreCloseTime, SaleTime
              datediff(mi, saletime, storeCloseTime) as timeDifference 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM