(问题与此类似,只是我的是 1-in Access,而不是 SQL Server,并且 2-仅检查一列是否有更改。)
以下是产品 (SKU) 的样本数据、购买日期和购买时的价格:
+----------------+------------+------------+
| SKU | Unit_Price | Date_Due |
+----------------+------------+------------+
| BHM1200NBACSTA | $13.00 | 11/2/2012 |
| BHM1200NBACSTA | $13.00 | 10/19/2012 |
| BHM1200NBACSTA | $13.00 | 9/28/2012 |
| BHM1200NBACSTA | $10.50 | 9/21/2012 |
| BHM1200NBACSTA | $13.00 | 8/27/2012 |
| BHM1200NBACSTA | $13.00 | 7/4/2012 |
| BHM1200NBACSTA | $12.50 | 6/19/2012 |
| BHM1700NDACSTA | $14.50 | 10/27/2012 |
| BHM1700NDACSTA | $14.73 | 9/29/2012 |
| BHM1700NDACSTA | $14.73 | 8/23/2012 |
| BHM1700NDACSTA | $14.50 | 6/20/2012 |
+----------------+------------+------------+
我只想查看任何给定日期范围的一个价格,因此以相同的价格多次购买了给定的产品,我只想查看该价格的该产品的第一个日期:
示例输出如下:
+----------------+------------+------------+
| SKU | Unit_Price | Date_Due |
+----------------+------------+------------+
| BHM1200NBACSTA | $13.00 | 9/28/2012 |
| BHM1200NBACSTA | $10.50 | 9/21/2012 |
| BHM1200NBACSTA | $13.00 | 7/4/2012 |
| BHM1200NBACSTA | $12.50 | 6/19/2012 |
| BHM1700NDACSTA | $14.50 | 10/27/2012 |
| BHM1700NDACSTA | $14.73 | 8/23/2012 |
| BHM1700NDACSTA | $14.50 | 6/20/2012 |
+----------------+------------+------------+
(请注意,价格可能会先涨后跌,然后再涨。我不仅想要为每种产品设置唯一的价格,还希望为每个连续的日期范围设置唯一的价格。)
到目前为止,我使用过:
SELECT hbp1.SKU, hbp1.Date_Due, hbp1.Unit_Price
FROM Historical_Buy_Prices AS hbp1
Left JOIN Historical_Buy_Prices AS hpb2
ON (hbp1.SKU = hpb2.SKU)
AND (hbp1.Date_Due + 1 = hpb2.Date_Due)
WHERE (hpb2.Date_Due IS NULL
OR hbp1.Unit_Price <> hbp2.Unit_Price)
ORDER BY hbp1.SKU, hbp1.Date_Due;
当我运行它时,在显示结果之前,Access 会提示我输入 hbp2.Unit_Price 的值,然后仍然返回重复项。
我敢肯定这是我错过的简单事情。你能帮忙吗?谢谢,
更新:要使用 ddl 创建表,请使用:
CREATE TABLE Historical_Buy_Prices (SKU Text, UNIT_PRICE Currency, DATE_DUE Date
);
要插入示例数据,请使用:
INSERT INTO Historical_Buy_Prices VALUES ("BHM1200NBACSTA", 13.00, #11/2/2012#);
INSERT INTO Historical_Buy_Prices VALUES ("BHM1200NBACSTA", 13.00, #10/19/2012#);
INSERT INTO Historical_Buy_Prices VALUES ("BHM1200NBACSTA", 13.00, #9/28/2012#);
INSERT INTO Historical_Buy_Prices VALUES ("BHM1200NBACSTA", 10.50, #9/21/2012#);
INSERT INTO Historical_Buy_Prices VALUES ("BHM1200NBACSTA", 13.00, #8/27/2012#);
INSERT INTO Historical_Buy_Prices VALUES ("BHM1200NBACSTA", 13.00, #7/4/2012#);
INSERT INTO Historical_Buy_Prices VALUES ("BHM1200NBACSTA", 12.50, #6/19/2012#);
INSERT INTO Historical_Buy_Prices VALUES ("BHM1700NDACSTA", 14.50, #10/27/2012#);
INSERT INTO Historical_Buy_Prices VALUES ("BHM1700NDACSTA", 14.73, #9/29/2012#);
INSERT INTO Historical_Buy_Prices VALUES ("BHM1700NDACSTA", 14.73, #8/23/2012#);
INSERT INTO Historical_Buy_Prices VALUES ("BHM1700NDACSTA", 14.50, #6/20/2012#);