LASt存储过程输出的6条记录

时间:2010-07-01 06:32:00

标签: sql-server

以下是存储过程和“我想获取最新的六个 每个客户的发票“

对于每个客户来说,可能会有更多的发票,但我必须要发现 哪个是最新的6个发票。

ALTER PROCEDURE [dbo].[SCA_M_CUSTSOINV_REFRESH]
  @COMP_CD NVARCHAR(20)='',
  @USER_CD NVARCHAR(20)='',
  @USER_TYPE NVARCHAR(1)=''
AS
SET NOCOUNT ON

DECLARE @SLSHIST_DATE NVARCHAR(10)

SELECT 
   @SLSHIST_DATE = CONVERT(NVARCHAR(10), DATEADD(MONTH,-SLSHIST_MTH,dbo.[GetCountryDate]()),120)
FROM SET_MASTER

WITH SUBQUERY AS 
(SELECT
   ROW_NUMBER() OVER (PARTITION BY A.CUST_CD ORDER BY C.INV_KEY DESC) "ROW_ID",
   A.CUST_CD,C.SO_KEY "TXN_KEY",
   C.INV_NO, C.INV_KEY, C.INV_DT, C.INV_STATUS, C.NET_TTL_TAX AS INV_AMT
 FROM 
    (SELECT DIST_CD, SLSMAN_CD, CUST_CD FROM T_CA_SLSMANCUST 
     WHERE DIST_CD = @COMP_CD AND SLSMAN_CD = @USER_CD) A
INNER JOIN TXN_INVOICE C ON C.CUST_CD=A.CUST_CD
                         AND C.INV_DT >= @SLSHIST_DATE
)
SELECT 
    CUST_CD, TXN_KEY, INV_NO, INV_KEY, INV_DT, INV_STATUS, INV_AMT,
    CASE ROW_ID WHEN 1 THEN 'Y' ELSE 'N' END "LAST_INV"
FROM SUBQUERY
ORDER BY CUST_CD,INV_KEY

2 个答案:

答案 0 :(得分:2)

您将ROW_ID ROW_NUMBER() OVER (PARTITION BY A.CUST_CD ORDER BY C.INV_KEY DESC),而最后一张发票是ROW_ID = 1,所以您不需要添加WHERE ROW_ID <= 6,如下所示吗?

   SELECT 
        CUST_CD, TXN_KEY, INV_NO, INV_KEY, INV_DT, INV_STATUS, INV_AMT,
        CASE ROW_ID WHEN 1 THEN 'Y' ELSE 'N' END "LAST_INV"
    FROM SUBQUERY
    WHERE ROW_ID <= 6
    ORDER BY CUST_CD,INV_KEY

答案 1 :(得分:0)

SELECT TOP 6 * FROM invoices ORDER BY date DESC