SQL Server:获取给定月份的行顺序号

时间:2018-11-29 07:30:23

标签: sql sql-server

我正在使用SQL Server并尝试获取一个月内的事务顺序,例如,如果一个月内有10个事务,我想知道所选事务是何时发生的,例如它是第一,第二,第三等。该月的交易。我尝试像

一样使用ROW_NUMBER()
SELECT
    transactionid, 
    ROW_NUMBER() OVER(ORDER BY transactionexecutiontime ASC) rowOrderNumber 
FROM   
    dbo.exportebop 
WHERE 
    MONTH(transactionexecutiontime) = 1 
ORDER BY 
    transactionexecutiontime ASC 

如果我没有指定TransactionID因为在我使用TransactionID = idNumber时得到多行,这会起作用,它返回单行并且row_number()始终为1

我知道ROW_NUMBER()对结果集进行计数,但是我需要一种方法来代替使用TransactionExecutionTime计算一个月中的订单号。

有人知道我能做到这一点吗?

2 个答案:

答案 0 :(得分:1)

我认为您需要先申请Row_Number,然后再申请filtering。我将使用CTE来做到这一点-

;WITH CTE AS (
    SELECT
        TransactionID,
        ROW_NUMBER()  OVER(ORDER BY TransactionExecutionTime ASC) rowOrderNumber
    FROM dbo.EXPORTEBOP
    WHERE MONTH(TransactionExecutionTime) = 1
)
SELECT *
FROM CTE
WHERE TransactionID = 1
ORDER BY rowOrderNumber ASC

作为子查询-

DECLARE @Month INT = 1
SELECT *
FROM (
    SELECT
        TransactionID,
        ROW_NUMBER()  OVER(ORDER BY TransactionExecutionTime ASC) rowOrderNumber
    FROM dbo.EXPORTEBOP
    WHERE MONTH(TransactionExecutionTime) = @Month
) X
WHERE TransactionID = 1
ORDER BY rowOrderNumber ASC

答案 1 :(得分:0)

如果要列出所有月份,则可以按月份对行号进行分区:

SELECT
    transactionid,
    Month = MONTH(transactionexecutiontime),
    rowOrderNumber = ROW_NUMBER() OVER(
        PARTITION BY
            MONTH(transactionexecutiontime) -- Will start different "row numbers" for each month
        ORDER BY 
            transactionexecutiontime ASC)
FROM   
    dbo.exportebop 
ORDER BY
    MONTH(transactionexecutiontime),
    transactionexecutiontime ASC

如果您想要一个特定的交易ID,则无法在与ROW_NUMBER()相同的结果集上进行过滤,因为它只会为该结果集生成一个行号,该行号仅包含1行(您的已过滤的交易)。您将不得不在引用第一个查询的另一个查询(使用CTE或子查询)上对其进行过滤:

;WITH RankedTransactionsByMonth AS
(
    SELECT
        transactionid, 
        Month = MONTH(transactionexecutiontime),
        rowOrderNumber = ROW_NUMBER() OVER(
            PARTITION BY
                MONTH(transactionexecutiontime) -- Will start different "row numbers" for each month
            ORDER BY 
                transactionexecutiontime ASC)
    FROM   
        dbo.exportebop 
    -- No Order by in subqueries without TOP!!
)
SELECT
    R.*
FROM
    RankedTransactionsByMonth AS R
WHERE
    R.transactionid = 1