选择表中列的前10行

时间:2019-04-09 16:03:11

标签: sql sql-server

请让我知道如何为下表中的每个客户选择前10行

SELECT [dt_dim_id],
       [cusip_num],
       sr.[product_dim_id],
       [acct_dim_id],
       [product_name]
FROM [csr_prod].[dbo].[stock_rec] AS sr,
     [csr_prod].[dbo].[product_dim] AS pd
WHERE sr.product_dim_id = pd.product_dim_id
  AND dt_dim_id = 20180927
ORDER BY dt_dim_id,
         product_dim_id,
         acct_dim_id;

2 个答案:

答案 0 :(得分:0)

使用apply

select . . .
from [csr_prod].[dbo].[stock_rec] sr cross apply
     (select top (10) pd.*
      from [csr_prod].[dbo].[product_dim] pd =
      where sr.product_dim_id = pd.product_dim_id and dt_dim_id = 20180927 
      order by ?  -- whatever column defines the first 10 records
     ) p

答案 1 :(得分:0)

使用ROW_NUMBER()对组进行分区并根据需要进行排序,然后过滤前10行:

;WITH paging AS
(
    SELECT ROW_NUMBER() OVER (PARTITION BY cusip_num 
                                  ORDER BY dt_dim_id, product_dim_id, acct_dim_id) n,
           [dt_dim_id],
           [cusip_num],
           sr.[product_dim_id],
           [acct_dim_id],
           [product_name]
      FROM [csr_prod].[dbo].[stock_rec] AS sr,
           [csr_prod].[dbo].[product_dim] AS pd
     WHERE sr.product_dim_id = pd.product_dim_id
       AND dt_dim_id = 20180927
)
SELECT * FROM paging WHERE n <= 10