用于按组排序的SQL条件

时间:2017-09-26 10:41:46

标签: sql sql-server

如何订购一些数据,基于StockID为3,并且在这种情况下还有两个仓库:WarehouseId 1和13,

from dateutil.parser import parse
parse("2015-10-1 3:00 PM GMT+1:00")

结果:

select ProductID, WarehouseID, StockID
from @allStocksState 
group by ProductID, WarehouseID, StockID
order by CASE WHEN StockID = 3 then 0
             else 1 
         end

所以在6995,7020,7031的情况下应该出现在最后,因为在这种情况下他们每个只有一个WarehouseId,所以我需要应用什么更改我的查询?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以在order by

中使用窗口函数
select ProductID, WarehouseID, StockID
from @allStocksState 
group by ProductID, WarehouseID, StockID
order by count(*) over (partition by productid) desc,
         (case when StockID = 3 then 0 else 1 end);

count(*) over (partition by productid)计算有多少行具有相同的productid

答案 1 :(得分:0)

select ProductID,WarehouseID,StockID from @allStocksState 
    group by ProductID,WarehouseID,StockID
    order by CASE WHEN StockID=3 then
    "ASC" else
    "DESC" end