带有JOIN的SQL max()

时间:2017-12-05 11:06:28

标签: sql sql-server join greatest-n-per-group

想请你帮忙

让我Sql query列出所有订单,但我需要添加OrderStatus OrderStatusID

SELECT DISTINCT 
    a.OrderNr, 
    a.CompanyName, 
    max(a.OrderStatusID) AS 'xxx'

FROM [NB].[dbo].[Npos] as a
INNER JOIN [NB].[dbo].[Npos_Order_Status_Name] as b 
ON 
a.OrderStatusID = b.OrderStatusID

GROUP BY  OrderNr, CompanyName
[NB].[dbo].[Npos_Order_Status_Name]中的

OrderStatusID | OrderStatusName
--------------------------------
            0 | Start
            1 | Stop
            2 | Pause

我用inner join尝试过,但我做错了。

谢谢

1 个答案:

答案 0 :(得分:1)

我相信这个查询会做你想做的事情

SELECT t.OrderNr, t.CompanyName, b.OrderStatusName
FROM
(
   SELECT 
    OrderNr, 
    CompanyName, 
    max(OrderStatusID) AS 'maxOrderStatus'
  FROM [NB].[dbo].[Npos]
  GROUP BY  OrderNr, CompanyName
) t
JOIN [NB].[dbo].[Npos_Order_Status_Name] as b 
  ON  t.maxOrderStatus = b.OrderStatusID

或使用窗口函数

SELECT t.*
FROM
(     
    SELECT
        a.*,
        row_number() over (partition by OrderNr, CompanyName order by OrderStatusID desc) rn
    FROM [NB].[dbo].[Npos] as a
    INNER JOIN [NB].[dbo].[Npos_Order_Status_Name] as b 
      ON a.OrderStatusID = b.OrderStatusID
) t
WHERE rn = 1

但是,根据我的经验,在某些情况下,第二种变体可能稍慢。