返回MIN Row_Number()SQL

时间:2019-02-08 14:31:49

标签: sql sql-server

这可能是我做过的最笨拙的查询。我必须使用只读帐户,因此无法使用临时表或任何其他方式来简化此操作。目标是在MIN(RowNum)时返回sumPiecesScrapped = maxSum。我尝试将整个查询添加到另一个子查询中,以尝试返回MIN(RowNum),但是它是一对多的,与主键JobNo绑定,当我将其绑定到{{1} }和JobNo的结果与下面的结果相同。

StepNo

结果:

SELECT
JobNo,
StepNo,
sumPiecesScrapped,
maxSum,
CASE
WHEN sumPiecesScrapped = maxSum THEN ROW_NUMBER() OVER(PARTITION BY JobNo ORDER BY JobNo, StepNo)
ELSE 0
END AS RowNum
FROM
(
    SELECT
    JobNo,
    StepNo,
    sumPiecesScrapped
    FROM
    (   
            SELECT
            JobNo,
            StepNo,
            SUM(PiecesScrapped) as sumPiecesScrapped
            FROM
            (
                SELECT
                JobNo,
                StepNo,
                PiecesFinished,
                PiecesScrapped
                FROM TimeTicketDet
            ) tt2

            GROUP BY JobNo, StepNo
    ) tt3
    GROUP BY JobNo, StepNo, sumPiecesScrapped
) tt4

LEFT JOIN
(
    SELECT
    JobNo as tt5JobNo,
    MAX(PiecesScrapped) as maxSum
    FROM
    (
        SELECT
        JobNo,
        PiecesScrapped
        FROM TimeTicketDet
    ) tt5
    GROUP BY JobNo
) tt5
ON tt5.tt5JobNo = tt4.JobNo


WHERE tt4.JobNo = '12345'

所需结果:

+-------+--------+-------------------+--------+--------+
| JobNo | StepNo | sumPiecesScrapped | maxSum | RowNum |
+-------+--------+-------------------+--------+--------+
| 12345 |     10 |                 0 |      5 |      0 |
| 12345 |     20 |                 1 |      5 |      0 |
| 12345 |     30 |                 5 |      5 |      3 |
| 12345 |     40 |                 5 |      5 |      4 |
| 12345 |     60 |                 5 |      5 |      5 |
| 12345 |     70 |                 5 |      5 |      6 |
+-------+--------+-------------------+--------+--------+

其他可能的结果:

+-------+--------+-------------------+--------+--------+
| JobNo | StepNo | sumPiecesScrapped | maxSum | RowNum |
+-------+--------+-------------------+--------+--------+
| 12345 |     10 |                 0 |      5 |      0 |
| 12345 |     20 |                 1 |      5 |      0 |
| 12345 |     30 |                 5 |      5 |      3 |
| 12345 |     40 |                 5 |      5 |      3 |
| 12345 |     60 |                 5 |      5 |      3 |
| 12345 |     70 |                 5 |      5 |      3 |
+-------+--------+-------------------+--------+--------+

0 个答案:

没有答案