[英]SQL Server function ROW_NUMBER() OVER (PARTITION BY not calc
I have problem with the ROW_NUMBER() OVER(PARTITION BY ....)
function. 我对
ROW_NUMBER() OVER(PARTITION BY ....)
函数有问题。
This is my original table which I work with: 这是我使用的原始表格:
PRODUCT VERSION Colour
------------------------------
Apple 7.1 Black
Apple 7.1 Blue
Apple 7.1 Red
Apple 2.0 NULL
Beer 12.8 Blue
Beer 12.8 NULL
Beer 12.8 NULL
Bread 14.87 Blue
Bread 14.87 NULL
Bread 14.87 Orange
Notes 100 Red
Notes 100 NULL
Car NULL Green
Car NULL Blue
Car NULL Red
Car NULL Red
I run this script against this table: 我针对此表运行此脚本:
SELECT
[product], [version], [colour],
ROW_NUMBER() OVER (PARTITION BY [product], [Version] ORDER BY [product] DESC) AS COUNT2
FROM
TABLE1
Then I get an output like this: 然后我得到这样的输出:
PRODUCT VERSION Colour COUNT2
-----------------------------------
Apple 7.1 Black 1
Apple 7.1 Blue 2
Apple 7.1 Red 3
Apple 2.0 NULL 4
Beer 12.8 Blue 1
Beer 12.8 NULL 2
Beer 12.8 NULL 3
Bread 14.87 Blue 1
Bread 14.87 NULL 2
Bread 14.87 Orange 3
Notes 100 Red 1
Notes 100 NULL 2
Car NULL Green 1
Car NULL Blue 2
Car NULL Red 3
Car NULL Red 4
Then I select rows with maximal values 然后我选择具有最大值的行
SELECT
[Product], [Version], MAX(COUNT2)
FROM
[dbo].[TABLE1]
GROUP BY
Product, Version
But here I have problem. 但是我有问题。 I can not get same numbers when I run function
ROW_NUMBER() OVER(PARTITION BY ...)
depend only on 1 column 运行函数
ROW_NUMBER() OVER(PARTITION BY ...)
时我无法获得相同的数字,仅取决于1列
I can not calculate back and get correct result if I calculate back way. 如果我计算回来的方法,我将无法计算回来并获得正确的结果。
PRODUCT VERSION COUNT2
----------------------------
Apple 7.1 6
Apple 2.0 7
Beer 12.8 5
Bread 14.87 1
Notes 100 6
Car NULL 8
If I run script without version on the end I am getting different numbers when I do calculation back way 如果我最后运行没有版本的脚本,那么在进行反向计算时会得到不同的数字
SELECT
[product], [version], [colour],
ROW_NUMBER() OVER(PARTITION BY [product], ORDER BY [product] DESC) AS COUNT2
FROM
TABLE1
SELECT
[Product], MAX(COUNT2)
FROM
[dbo].[TABLE1]
GROUP BY
Product
Result is different than what I am expecting: 结果与我预期的不同:
PRODUCT COUNT
----------------
Apple 4
Beer 3
Bread 3
Notes 2
Car 4
I expected a result like this : 我期望这样的结果:
PRODUCT VERSION COUNT2
----------------------------
Apple 7.1 3
Apple 2.0 1
Beer 12.8 3
Bread 14.87 3
Notes 100 2
Car NULL 4
Thanks for help me to setup function ROW_NUMBER() OVER(PARTITION BY....)
感谢您的帮助,我设置了函数
ROW_NUMBER() OVER(PARTITION BY....)
Original table has over 10000 rows.. 原始表有10000多行。
Just add count()along with partition for your query 只需添加count()以及查询分区
Select PRODUCT,[VERSION], COUNT2 from (
Select DISTINCT
PRODUCT,
VERSION,
Count(COUNT2)OVER(PARTITION BY version )COUNT2 from (
SELECT
[product],
[version],
[colour],
ROW_NUMBER() OVER (PARTITION BY [product], [Version] ORDER BY [product] DESC) AS COUNT2
FROM
@Table1 )T
GROup BY PRODUCT, VERSION,COUNT2 )TT
ORDER BY CASE WHEN VERSION IS NOT NULL then 0 else 1 END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.