以下是我的表数据
Mat Phy Chem
20 30 40
25 35 35
45 30 30
45 40 35
我想在一行中检索所有三列中的前三行。
O / P
Mat Phy Chem
45 40 40
25 35 35
20 30 30
我使用过以下查询但未成功,请帮助...
Select distinct top 3 max(mat) from studata group by mat order by max(mat) desc
Union all
Select distinct top 3 max(phy) from studata group by phy order by max(phy) desc
Union all
Select distinct top 3 max(chem) from studata group by chem order by max(chem) desc
答案 0 :(得分:2)
WITH q AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY mat DESC) AS rn_mat,
ROW_NUMBER() OVER (ORDER BY phy DESC) AS rn_phy,
ROW_NUMBER() OVER (ORDER BY chem DESC) AS rn_chem
FROM mytable
)
SELECT q_mat.mat, q_phy.phy, q_chem.chem
FROM q q_mat
JOIN q q_phy
ON q_phy.rn_phy = q_mat.rn_mat
JOIN q q_chem
ON q_chem.rn_chem = q_phy.rn_phy
WHERE q_mat.rn_mat <= 3
答案 1 :(得分:0)
这有用吗?
select distinct top 3 Mat
from studata
order by Mat desc
select distinct top 3 Phy
from studata
order by Phy desc
select distinct top 3 Chem
from studata
order by Chem desc
你可能遇到问题的原因是因为max是一个函数(它只返回1个东西)所以Select distinct top 3 max(mat)
是无意义的。