从 SQL 中的多个表返回最大价格日期的问题
Posted
技术标签:
【中文标题】从 SQL 中的多个表返回最大价格日期的问题【英文标题】:Issues returning max date for price from multiple tables in SQL 【发布时间】:2020-10-03 20:57:12 【问题描述】:第一次发帖,对 SQL 比较陌生,所以请善待:D
我尝试将股票列表拉到一起的 SQL 查询存在问题。
我需要从 StockItem_Pricing 表中提取具有最后修改日期的 SalePrice。
我已将到目前为止的查询包含在下面。
SELECT
sc.ChannelSKU AS 'sku',
cb.Level_LessOrderBook AS 'quantity',
cb.InOrderBook AS 'In Open Orders',
cb.MinimumLevel AS 'Minimum Level',
cb.Level AS 'Stock Level',
si.BarcodeNumber AS 'Barcode Number',
sp.SalePrice AS 'product_price_vat_inc',
sp.SalePrice AS 'Retail Price',
cb.ItemTitle AS 'Title',
sc.Source,
sc.SubSource,
sp.ModifiedDate AS 'LastUpdate'
FROM
Stock_ChannelSKU sc
INNER JOIN
View_CombinedStock cb ON cb.pkStockItemId = sc.fkStockItemId
INNER JOIN
StockItem si ON si.pkStockItemID = sc.fkStockItemId
INNER JOIN
StockItem_Pricing sp ON sp.fkStockItemId = sc.fkStockItemId
WHERE
sc.SubSource = 'UM_8292775'
提前致谢:D
【问题讨论】:
你能更新你得到的错误吗?还是您所期望的,但实际发生了什么? 【参考方案1】:如果你只想要一行,那么使用TOP()
和ORDER BY
:
select top (1)
sc.ChannelSKU AS sku,
cb.Level_LessOrderBook AS quantity,
cb.InOrderBook AS InOpenOrders,
cb.MinimumLevel AS MinimumLevel,
cb.Level AS StockLevel,
si.BarcodeNumber AS BarcodeNumber,
sp.SalePrice AS product_price_vat_inc,
sp.SalePrice AS RetailPrice,
cb.ItemTitle AS Title,
sc.Source,
sc.SubSource,
sp.ModifiedDate as LastUpdate
from Stock_ChannelSKU sc
inner join View_CombinedStock cb on cb.pkStockItemId = sc.fkStockItemId
inner join StockItem si on si.pkStockItemID = sc.fkStockItemId
inner join StockItem_Pricing sp on sp.fkStockItemId = sc.fkStockItemId
where sc.SubSource = 'UM_8292775'
order by sp.ModifiedDate desc
如果您想要每个 sku 的最新行,那么另一种选择是 row_number()
:
select *
from (
select
sc.ChannelSKU AS sku,
cb.Level_LessOrderBook AS quantity,
cb.InOrderBook AS InOpenOrders,
cb.MinimumLevel AS MinimumLevel,
cb.Level AS StockLevel,
si.BarcodeNumber AS BarcodeNumber,
sp.SalePrice AS product_price_vat_inc,
sp.SalePrice AS RetailPrice,
cb.ItemTitle AS Title,
sc.Source,
sc.SubSource,
sp.ModifiedDate as LastUpdate,
row_number() over(partition by sc.ChannelSKU order by sp.ModifiedDate desc) rn
from Stock_ChannelSKU sc
inner join View_CombinedStock cb on cb.pkStockItemId = sc.fkStockItemId
inner join StockItem si on si.pkStockItemID = sc.fkStockItemId
inner join StockItem_Pricing sp on sp.fkStockItemId = sc.fkStockItemId
where sc.SubSource = 'UM_8292775'
) t
where rn = 1
【讨论】:
谢谢!我可能应该更清楚,我只需要返回每个 SKU 的最后修改价格。这样我就可以导出他们需要列出的所有 sku 的每小时库存提要的结果以上是关于从 SQL 中的多个表返回最大价格日期的问题的主要内容,如果未能解决你的问题,请参考以下文章
SQL从日期范围内的同一表中的不同记录中获取多个项目的总和(ORACLE)