SQL Query根据另一个字段中的值返回最后一个ID

时间:2015-10-06 23:09:07

标签: sql sql-server

我试图获取" MenuItem.MenuID"的最后一个ID。因为它是该类型的最新版本,因为每个市场有多个Menu.Names。如何获得每个菜单中每个菜单的最新ID以及该菜单中的所有项目?

SELECT 
    MenuItem.MenuId, Menu.Name, MenuItem.ProductId, Product.Name,
    MenuItem.Count,Menu.MenuTypeId, MenuType.MarketId, Available,
    StandardItem,  UnitsPerPackage, ItemWeighting, Product.Disabled, ExtraItem
FROM MenuItem 
JOIN Menu 
  ON MenuItem.MenuId = Menu.Id 
JOIN ProducT 
  ON MenuItem.ProductId = Product.Id 
JOIN MenuType
  ON MenuType.Id = MENU.MenuTypeId
WHERE MenuType.Disabled = 0
  AND product.Disabled = 0 
  AND MENU.NAME = 'a generic menu' 
  AND MenuType.MarketId = 1
ORDER BY 
    MarketId,
    MENU.ID,
    MenuTypeId;  

1 个答案:

答案 0 :(得分:0)

SELECT TOP 1
  MenuItem.MenuId, Menu.Name, MenuItem.ProductId, Product.Name,
  MenuItem.Count,Menu.MenuTypeId, MenuType.MarketId, Available,
  StandardItem,  UnitsPerPackage, ItemWeighting, Product.Disabled, ExtraItem
FROM 
  MenuItem 
  INNER JOIN Menu ON MenuItem.MenuId = Menu.Id 
  INNER JOIN ProducT ON MenuItem.ProductId = Product.Id 
  INNER JOIN MenuType ON MenuType.Id = MENU.MenuTypeId
WHERE
  MenuType.Disabled=0 AND product.Disabled=0 
  AND MENU.NAME = 'a generic menu' AND MenuType.MarketId=1
ORDER BY 
  MarketId, MENU.ID, MenuTypeId 

<强>更新

如果你想为每个市场返回顶部,你可以使用这样的公用表格式:

WITH MyMenus AS
(
   SELECT *,
         ROW_NUMBER() OVER (PARTITION BY MenuType.MarketId ORDER BY Menu.Id, Menu.MenuTypeId) AS rowNumber
   FROM MenuItem
     INNER JOIN Menu ON MenuItem.MenuId = Menu.Id
     INNER JOIN Product ON MenuItem.ProductId = Product.Id
     INNER JOIN MenuType ON MenuType.Id = Menu.MenuTypeId
   WHERE
     MenuType.Disabled=0 AND product.Disabled=0
     AND Menu.Name = 'a generic menu'
)
SELECT *
FROM MyMenus
WHERE rowNumber = 1