匹配SQL查询中的字段

时间:2017-07-26 17:28:34

标签: sql oracle

我正在编写一个将从数据库生成报告的查询,但我遇到了以下问题。我生成的报告从存储商品价格历史的表中提取数据。客户想要添加一个列,其中显示该项目的当前价格,这是具有最新生效日期的价格。但是,我对如何说出来感到茫然。

释义,这就是我目前所拥有的

SELECT
  Items.Item_Name as "Name",
  Items.Item_Desc as "Description",
  Items.Item_Price as "Price",
  Items.Item_Date as "Date"
FROM
  Items
WHERE
  Date between '01/01/2017' AND '01/31/2017';

到目前为止,这将返回1月份更改的所有项目。但是,我想在显示当前价格时添加列,以及列出当前价格的列。像这样:

--------------------------------------------------------------------------
|  Item  |  Description  |   Price   |   Date   |  CurPrice  |  CurDate  |
|--------|---------------|-----------|----------|------------|-----------|
|  Item1 |      Desc1    |  Price1.2 |  Date1.2 | Price1July | Date1July |
|  Item2 |      Desc2    |  Price2.1 |  Date2.1 | Price2July | Date2July |
|  Item1 |      Desc1    |  Price1.1 |  Date1.1 | Price1July | Date1July |
--------------------------------------------------------------------------

基本上,我应该看到每个项目的所有更改,但是反映该项目的当前日期/价格的单元格对于任何给定的项目实例应该是相同的。我该怎么做?谢谢!

2 个答案:

答案 0 :(得分:0)

我不知道SQL * Plus是否支持子查询,但如果确实如此,这是一个可能的解决方案。

SELECT  Items.Item_Name as "Name",
        Items.Item_Desc as "Description",
        Items.Item_Price as "Price",
        Items.Item_Date as "Date",
        (SELECT Item_Price 
         FROM ( SELECT Sub.Item_Price
                FROM Items AS Sub
                WHERE Items.Item_Name = Sub.Item_Name
                AND Sub.Item_Date <= GETDATE()
                ORDER BY Items.Item_Date DESC)
          WHERE ROWNUM = 1 ) AS CurrentPrice,
        (SELECT Item_Date 
         FROM ( SELECT Sub.Item_Date
                FROM Items AS Sub
                WHERE Items.Item_Name = Sub.Item_Name
                AND Sub.Item_Date <= GETDATE()
                ORDER BY Items.Item_Date DESC)
          WHERE ROWNUM = 1 ) AS CurrentDateEffectiveDate
FROM Items
WHERE [Date] between '01/01/2017' AND '01/31/2017';

我们使用子查询来获取项目的最新价格 示例:如果今天没有价格,它将使用昨天的价格。

答案 1 :(得分:0)

你应该使用 ROW_NUMBER() OVER (PARTITION BY [PARTITION_COL] ORDER BY [Order_Col] asc/desc) AS [Col_Name]。 在你的情况下,它将是

SELECT * 
FROM   (SELECT items.item_name              AS "Name", 
               items.item_desc              AS "Description", 
               items.item_price             AS "Price", 
               items.item_date              AS "Date", 
               Row_number() 
                 OVER( 
                   partition BY item_name 
                   ORDER BY item_date DESC) AS Num 
        FROM   items 
        WHERE  date BETWEEN '01/01/2017' AND '01/31/2017')t1 
WHERE  num = 1