SQL Server在同一表上使用不同的select语句,结果不同

时间:2019-07-13 16:26:04

标签: sql sql-server database web-applications

我有一个产品表,其中包含创建日期,价格,价格,.......和多列。我需要一个选择语句,该语句返回10条最新记录,10条最低价格和评价最高的产品彼此分开的结果

(select top 10 from products Order By Date ASC ) as newest_list
(select top 10 from products Order By price DESC ) as price_list
(select top 10 from products Order By Rate ASC ) as rateList_list 

其中(newest_list price_list rateList_list)是不同的表结果

采用哪种更好的方法来解决这个问题。谢谢。

1 个答案:

答案 0 :(得分:0)

您基本上想要union all。 。 。和一个子查询:

select *
from ((select top 10 'newest' as which, p.*
       from products p
       Order By Date ASC
      ) union all
      (select top 10 'priciest', p.*
       from products p
       Order By price DESC
      ) union all
      (select top 10 'ratiest', p.*
       from products p
       Order By Rate ASC
      )
     ) p

如果您不想重复,可以使用union或窗口函数:

select p.*
from (select p.*,
             row_number() over (order by date desc) as seqnum_d,
             row_number() over (order by price desc) as seqnum_p,
             row_number() over (order by rate asc) as seqnum_r
      from p
     ) p
where seqnum_d <= 10 or seqnum_p <= 10 or seqnum_r <= 10;