简体   繁体   中英

Trouble getting SQL Server subquery to pick desired results

I am given a database to use in SQL server. The tables are:

  • Price (prodID, from, price)
  • Product (prodID, name, quantity)
  • PO (prodID, orderID, amount)
  • Order (orderID, date, address, status, trackingNumber, custID, shipID)
  • Shipping (shipID, company, time, price)
  • Customer (custID, name)
  • Address (addrID, custID, address)

I need to Determine the ID and current price of each product.

The from attribute in the Price table are the dates that the prices were updated ie each ID in the table has multiple prices and dates associated with them but there is no common date between all of the IDs and the dates are in the 'YYYY-MM-DD' format and range is from 2018 to 2019-12-31.

My current query looks like:

select distinct p.prodID, p.price
from Price as p
where p.[from] >= '2019-12-23' and p.[from] in (select [from]
from Price
group by [from]
having max([from]) <= '2019-12-31')
order by p.prodID;

which returns a table with multiple prices for some of the IDs and also excludes other IDs altogether.

I was told that I needed a subquery to perform this.

I believe that I may be being too specific in my query to produce the desired results.

My main goal is to fix my current query to select one of each prodID and price from the most recent from date.

One option uses window functions:

select *
from (
    select p.*, row_number() over(partition by p.prodid order by p.from desc) rn
    from price p
    where p.from <= convert(date, getdate())
) t
where rn = 1

This returns the latest row for each prodid where from is not greater that the current date.

As an alternative, you could also use with ties :

select top (1) with ties p.*
from price p
where p.from <= convert(date, getdate())
order by row_number() over(partition by p.prodid order by p.from desc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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