Первый постер и новичок в SQL, так что будьте любезны: D

У меня проблема с SQL-запросом, который я пытаюсь составить, чтобы собрать список акций.

Мне нужно вытащить SalePrice с последней измененной датой из таблицы StockItem_Pricing.

Я включил запрос, который у меня до сих пор, ниже.

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'

Заранее спасибо

0
Liam Cole 3 Окт 2020 в 23:57

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

Если вам нужна последняя строка на артикул , альтернативой является 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
0
GMB 3 Окт 2020 в 21:15