在 UNION 之后创建排名列

Creating a rank column after UNION

我正在尝试根据第 SalesAmount 列中的金额创建一个 SalesRank 列。

我正在尝试做与此类似的事情:RANK() OVER(Order BY SalesAmount desc) as StateRank,但我不确定在将两个 table 连接在一起后如何执行此操作?如何在合并 table 后创建另一列?为此,我需要将联合 select 插入 #temptable?

这是我的例子 table:

StateId ReportTitle ReportId SalesAmount
1 Online Sales in California 21 21512
12 Online Sales in New York 37 13201
14 Online Sales in Michigan 91 9212
23 Online Sales in Nevada 14 12931
8 Online Sales in Pennsylvania 14 23413
13 Online Sales in Oregon 14 9651

我期待 return 喜欢:

StateId ReportTitle ReportId SalesAmount SalesRank
1 Online Sales in California 21 21512 2
12 Online Sales in New York 37 13201 3
14 Online Sales in Michigan 91 9212 6
23 Online Sales in Nevada 14 12931 4
8 Online Sales in Pennsylvania 14 23413 1
13 Online Sales in Oregon 14 9651 5

这是我的查询:

CREATE TABLE TableOne
(
    StateId INT,
    ReportTitle VARCHAR(100),
    ReportId INT,
    SalesAmount Money, 
)

INSERT INTO TableOne (StateId,ReportTitle,ReportId,SalesAmount)
VALUES (1,'Online Sales in California',21, 21512),(12,'Online Sales in New York',37,13201), (14,'Online Sales in Michigan',91,9212)

CREATE TABLE TableTwo
(
    StateId INT,
    ReportTitle VARCHAR(100),
    ReportId INT,
    SalesAmount Money, 
)

INSERT INTO TableTwo (StateId,ReportTitle,ReportId,SalesAmount)
VALUES (23,'Online Sales in Nevada',14,12931), (8,'Online Sales in Pennsylvania',14,23413), (13,'Online Sales in Oregon',14,9651)

SELECT * FROM TableOne 
UNION ALL 
SELECT * FROM TableTwo

你快到了。

SELECT  *
        ,RANK() OVER (ORDER BY SalesAmount DESC) AS RowRank
FROM    (
            SELECT  *
            FROM    TableOne
            UNION ALL
            SELECT  *
            FROM    TableTwo
        ) AS t;

或者您可以使用 Common Table Expression(在这种情况下只是 neater/different 编写子查询的方式,但在其他情况下确实提供更多好处)。

WITH cte AS (
  SELECT *
  FROM TableOne
  UNION ALL
  SELECT *
  FROM TableTwo
)
SELECT *
     , RANK() OVER (ORDER BY SalesAmount DESC) AS RowRank
FROM cte;