在这里寻找一些关于我目前正在进行的项目的建议。
我有一张桌子
车辆名称
合同数量
销售金额
的比率
我想根据某些条件在表格中添加行号。
如果有5辆或更多车辆比率 = 0则RowNumber()超过销售金额,但只应用行号比率 = 0
“其他一切”RowNumber()OVER订购比率
我希望行号继续将行号应用于“其他所有内容”时重新开始。因此,如果满足条件,则使用销售金额应用RowNumber,其中比率 = 0。根据比率对其余部分进行排序。行号必须是连续的,不能重新开始。
如果上述条件失败,则只需使用RowNumber()按订单按比率
我基本上想要做的是在第一个失败的情况下为排名添加第二个条件。因此,如果条件1失败,则排在第二个条件下。
我会粘贴一张桌子,但只是意识到在这里获取一张桌子有多复杂。遗憾!
这是我尝试但没有奏效的一个例子。如果case语句为真,它会继续使用Ratio应用行号。
Select
,ROW_NUMBER()
OVER
(ORDER BY
(CASE WHEN SUM(CASE WHEN RATIO = 0 THEN 1 ELSE 0 END) >= 5
THEN Sale_Amount
ELSE Ratio END) ASC
)as Rows1
FROM Table
如果在这种情况下RowNumber()是最好的,那就不确定了。
任何答案或提示都会有所帮助!提前谢谢!
这是尝试显示我的数据:
原始数据集:
+---------+----------------+-------------+--------+
| Vehicle | # of Contracts | Sale Amount | Ratio |
+---------+----------------+-------------+--------+
| A | 1 | $800 | 0.00% |
| B | 1 | $800 | 0.00% |
| C | 1 | $978 | 0.00% |
| D | 4 | $2,069 | 0.00% |
| E | 2 | $1,600 | 0.00% |
| F | 6 | $4,210 | 0.00% |
| G | 3 | $1,289 | 0.00% |
| H | 5 | $1,590 | 0.00% |
| I | 10 | $8,456 | 13.45% |
| J | 12 | $9,000 | 10.56% |
| K | 6 | $2,458 | 20.00% |
| L | 9 | $3,607 | 34.50% |
| M | 10 | $7,987 | 70.80% |
| N | 2 | $954 | 96.89% |
| O | 2 | $800 | 34.67% |
| P | 3 | $800 | 23.09% |
| Q | 5 | $901 | 12.78% |
| R | 7 | $1,008 | 45.78% |
| T | 9 | $765 | 20.00% |
| U | 2 | $345 | 1.00% |
| V | 4 | $834 | 45.00% |
+---------+----------------+-------------+--------+
预期结果:
+-----------+---------+----------------+-------------+--------+
| RowNumber | Vehicle | # of Contracts | Sale Amount | Ratio |
+-----------+---------+----------------+-------------+--------+
| 1 | F | 6 | $4,210 | 0.00% |
| 2 | H | 5 | $1,590 | 0.00% |
| 3 | D | 4 | $2,069 | 0.00% |
| 4 | G | 3 | $1,289 | 0.00% |
| 5 | E | 2 | $1,600 | 0.00% |
| 6 | A | 1 | $800 | 0.00% |
| 7 | B | 1 | $800 | 0.00% |
| 8 | C | 1 | $978 | 0.00% |
| 9 | U | 2 | $345 | 1.00% |
| 10 | J | 12 | $9,000 | 10.56% |
| 11 | Q | 5 | $901 | 12.78% |
| 12 | I | 10 | $8,456 | 13.45% |
| 13 | K | 6 | $2,458 | 20.00% |
| 14 | T | 9 | $765 | 20.00% |
| 15 | P | 3 | $800 | 23.09% |
| 16 | L | 9 | $3,607 | 34.50% |
| 17 | O | 2 | $800 | 34.67% |
| 18 | V | 4 | $834 | 45.00% |
| 19 | R | 7 | $1,008 | 45.78% |
| 20 | M | 10 | $7,987 | 70.80% |
| 21 | N | 2 | $954 | 96.89% |
+-----------+---------+----------------+-------------+--------+
答案 0 :(得分:1)
您可以使用SUM OVER()
和ROW_NUMBER()
根据您的结果,我按照合约DESC 订购第一个标准。
WITH Cte AS(
SELECT *,
ZeroRatio = SUM(CASE WHEN Ratio = 0 THEN 1 ELSE 0 END) OVER()
FROM TestData
),
CteRN AS(
SELECT *,
RN = ROW_NUMBER() OVER(ORDER BY
CASE WHEN ZeroRatio >= 5 AND Ratio = 0 THEN NumContracts END DESC,
Ratio
)
FROM Cte
)
SELECT
RN, Vehicle, NumContracts, SaleAmount, Ratio
FROM CteRN
ORDER BY RN
答案 1 :(得分:0)
我认为您的示例输出不符合您所说的内容,因此可能需要调整ORDER BY
字段,但这是我认为您正在追求的内容:
;with cte AS (SELECT *,COUNT(*) OVER(PARTITION BY Ratio) AS Ratio_CT
FROM Table1
)
SELECT *,ROW_NUMBER() OVER(ORDER BY CASE WHEN Ratio_CT >= 5 AND Ratio = 0 THEN [Sale Amount] END DESC,Ratio) AS Rows1
FROM cte
演示:SQL Fiddle