考虑一个像
tbl_ranks -------------------------------- family_id | item_id | view_count -------------------------------- 1 10 101 1 11 112 1 13 109 2 21 101 2 22 112 2 23 109 3 30 101 3 31 112 3 33 109 4 40 101 4 51 112 4 63 109 5 80 101 5 81 112 5 88 109
我需要为按视图计数排序的家庭ID子集(例如1,2,3和4)的前两(2)行生成一个结果集。我想做类似的事情
select top 2 * from tbl_ranks where family_id = 1 order by view_count union all select top 2 * from tbl_ranks where family_id = 2 order by view_count union all select top 2 * from tbl_ranks where family_id = 3 order by view_count union all select top 2 * from tbl_ranks where family_id = 4 order by view_count
但是,当然, 按 这种方式在 所有 上下文中并不能有效。有什么建议?我知道我可以运行一组4个查询,将结果存储到临时表中,然后选择该临时表的内容作为最终结果,但我宁愿避免使用临时表。
注意:在实际应用中,每个家庭ID的记录数是不确定的,并且view_counts也不固定,如上例所示。
您可以尝试这样的事情
DECLARE @tbl_ranks TABLE( family_id INT, item_id INT, view_count INT ) INSERT INTO @tbl_ranks SELECT 1,10,101 INSERT INTO @tbl_ranks SELECT 1,11,112 INSERT INTO @tbl_ranks SELECT 1,13,109 INSERT INTO @tbl_ranks SELECT 2,21,101 INSERT INTO @tbl_ranks SELECT 2,22,112 INSERT INTO @tbl_ranks SELECT 2,23,109 INSERT INTO @tbl_ranks SELECT 3,30,101 INSERT INTO @tbl_ranks SELECT 3,31,112 INSERT INTO @tbl_ranks SELECT 3,33,109 INSERT INTO @tbl_ranks SELECT 4,40,101 INSERT INTO @tbl_ranks SELECT 4,51,112 INSERT INTO @tbl_ranks SELECT 4,63,109 INSERT INTO @tbl_ranks SELECT 5,80,101 INSERT INTO @tbl_ranks SELECT 5,81,112 INSERT INTO @tbl_ranks SELECT 5,88,109 SELECT * FROm ( SELECT *, ROW_NUMBER() OVER(PARTITION BY family_id ORDER BY view_count DESC) MyOrder FROM @tbl_ranks ) MyOrders WHERE MyOrder <= 2