简体   繁体   English

查询日期范围内产品的价格

[英]Querying for price of a product within a date range

在此处输入图像描述

I have to find the average price of iPhone Xs from this table within 1 August 2021 and 31 August 2021. So the records that I have narrowed down are 8, 9, 11 and 12. However records 8 and 9's StartDateTime and EndDateTime are outside of 1st and 31st August 2021, but still run through August 2021.我必须从这个表中找到 2021 年 8 月 1 日和 2021 年 8 月 31 日之间的 iPhone Xs 的平均价格。所以我缩小的记录是 8、9、11 和 12。但是记录 8 和 9 的 StartDateTime 和 EndDateTime 在外面2021 年 8 月 1 日至 31 日,但仍将持续到 2021 年 8 月。

So far, I am only able to query for records 11 and 12. Which is more straightforward:到目前为止,我只能查询记录 11 和 12。哪个更直接:

SELECT *
FROM dbo.PriceHistory
WHERE 
  PName = 'iPhone Xs' 
  AND StartDateTime BETWEEN '2021-08-01 00:00:00.000' AND '2021-08-31 00:00:00.000';

How should I query so that I can get records 8 and 9 as well?我应该如何查询才能同时获得记录 8 和 9?

Based on the desired behaviour you've described, you probably want to check if the start date is before September 1, and the end date is after August 1. This will get all items whose date ranges overlap with August.根据您描述的所需行为,您可能想要检查开始日期是否在 9 月 1 日之前,结束日期是否在 8 月 1 日之后。这将获取日期范围与 8 月重叠的所有项目。

So:所以:

SELECT *
FROM dbo.PriceHistory
WHERE 
  PName = 'iPhone Xs' 
  AND StartDateTime < '2021-09-01 00:00:00.000'
  AND EndDateTime >= '2021-08-01 00:00:00.000';

(Note that the upper endpoint should be September 1 to ensure we include the last day of August.) (请注意,上限应该是 9 月 1 日,以确保我们包括 8 月的最后一天。)

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

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