1. 程式人生 > 其它 >mysql 查詢資料帶排行 當出時相同時 則排名相同 排行榜帶分頁

mysql 查詢資料帶排行 當出時相同時 則排名相同 排行榜帶分頁

-- 此處select是為了分頁
SELECT
	* 
FROM
	(
	-- 此處select是為了增加排行 且 當前一個與當前出庫數量相同則不增加排行
	SELECT
		bb.*,
		( IF ( @pre_out_stock_num <> bb.out_stock_num, @rank := @rank + 1, @rank ) ) shipping_rank,
		@pre_out_stock_num := bb.out_stock_num AS temp 
	FROM
		(
		(
		-- 此處select是查出具體出庫數量,出庫金額,累計進出庫數量
		SELECT
			SUM( op.exchange_out_stock_num ) AS out_stock_num,
			SUM( op.out_stock_price ) AS out_stock_price,
			SUM( op.exchange_show_num ) AS exchange_show_num,
			gw.wine_name 
		FROM
			-- 訂單拆分表 拆出入庫 出庫資訊
			u_order_split AS op
			-- 關聯查到商品資訊
			LEFT JOIN u_goods_support gs ON gs.prod_id = op.prod_id
			-- 關聯查到酒體資訊
			LEFT JOIN u_goods_wine AS gw ON gw.wine_code = gs.wine_code 
		WHERE
			-- 業務判斷
			op.product_type = 1 
			AND op.ddate >= "2022-03-01" 
			AND op.ddate <= "2022-03-31" 
			-- 根據酒體分組
		GROUP BY gs.wine_code 
		HAVING gs.wine_code IS NOT NULL AND out_stock_num > 0 
		ORDER BY
			out_stock_num DESC 
	) AS bb,
	( SELECT @rank := 0 ) AS a,
	( SELECT @pre_out_stock_num := 0 ) AS b 
	) 
	) AS cc 
LIMIT 0,3