首页 > 代码库 > 分组 根据某一列进行排序,根据shopid分组,用createTime排序,返回row_number()序号 select no =row_number() over (partition by shopId order by createTime desc), * from Goods_info
分组 根据某一列进行排序,根据shopid分组,用createTime排序,返回row_number()序号 select no =row_number() over (partition by shopId order by createTime desc), * from Goods_info
over不能单独使用,要和分析函数:rank(),dense_rank(),row_number()等一起使用。
其参数:over(partition by columnname1 order by columnname2)
含义:按columname1指定的字段进行分组排序,或者说按字段columnname1的值进行分组排序。
例如:employees表中,有两个部门的记录:department_id =10和20
select department_id,rank() over(partition by department_id order by salary) from employees就是指在部门10中进行薪水的排名,在部门20中进行薪水排名。如果是partition by org_id,则是在整个公司内进行排名。
以下是个人见解:
sql中的over函数和row_numbert()函数配合使用,可生成行号。可对某一列的值进行排序,对于相同值的数据行进行分组排序。
执行语句:select row_number() over(order by AID DESC) as rowid,* from bb
SELECT
House.HouseId,
House.HouseName,
House.iconFlag,
House.orderId,
House.HouseJingYingFW,
House.HouseTel,
House.HouseCelPhone,
dbo.fnGetDistance(
118.328213, 35.081728, House.longitude,
House.latitude
) as jl,
Goods.originalPrice as levelCount,
Goods.presentPrice as levelAmount
FROM
House
LEFT JOIN (
select shopId,originalPrice,presentPrice
from (select no =row_number() over (partition by shopId order by createTime desc), * from Goods_info WHERE IsClear = 1)t
where no=1
) Goods on shopId = House.HouseId
where
(
House.isdel is null
or House.isdel = 0
)
and House.status = 1
and House.houseStatus <> 0
and House.housetype like ‘%1%‘
order by
House.orderId desc,
jl ASC
IF OBJECT_ID (‘dbo.fnGetDistance‘) IS NOT NULL
DROP FUNCTION dbo.fnGetDistance
GO
--计算地球上两个坐标点(经度,纬度)之间距离sql函数
CREATE FUNCTION [dbo].[fnGetDistance](@LatBegin REAL, @LngBegin REAL, @LatEnd REAL, @LngEnd REAL) RETURNS FLOAT
AS
BEGIN
--距离(千米)
DECLARE @Distance REAL
DECLARE @EARTH_RADIUS REAL
SET @EARTH_RADIUS = 6378.137
DECLARE @RadLatBegin REAL,@RadLatEnd REAL,@RadLatDiff REAL,@RadLngDiff REAL
SET @RadLatBegin = @LatBegin *PI()/180.0
SET @RadLatEnd = @LatEnd *PI()/180.0
SET @RadLatDiff = @RadLatBegin - @RadLatEnd
SET @RadLngDiff = @LngBegin *PI()/180.0 - @LngEnd *PI()/180.0
SET @Distance = 2 *ASIN(SQRT(POWER(SIN(@RadLatDiff/2), 2)+COS(@RadLatBegin)*COS(@RadLatEnd)*POWER(SIN(@RadLngDiff/2), 2)))
SET @Distance = @Distance * @EARTH_RADIUS
--SET @Distance = Round(@Distance * 10000) / 10000
RETURN @Distance
END
GO
SQL中Group分组获取Top N方法实现
分组 根据某一列进行排序,根据shopid分组,用createTime排序,返回row_number()序号 select no =row_number() over (partition by shopId order by createTime desc), * from Goods_info