![](/img/trans.png)
[英]I need a Row_number over partition to achieve this in SQL Server
[英]SQL Server function ROW_NUMBER() OVER (PARTITION BY not calc
我对ROW_NUMBER() OVER(PARTITION BY ....)
函数有问题。
这是我使用的原始表格:
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
我针对此表运行此脚本:
SELECT
[product], [version], [colour],
ROW_NUMBER() OVER (PARTITION BY [product], [Version] ORDER BY [product] DESC) AS COUNT2
FROM
TABLE1
然后我得到这样的输出:
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
然后我选择具有最大值的行
SELECT
[Product], [Version], MAX(COUNT2)
FROM
[dbo].[TABLE1]
GROUP BY
Product, Version
但是我有问题。 运行函数ROW_NUMBER() OVER(PARTITION BY ...)
时我无法获得相同的数字,仅取决于1列
如果我计算回来的方法,我将无法计算回来并获得正确的结果。
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
如果我最后运行没有版本的脚本,那么在进行反向计算时会得到不同的数字
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
结果与我预期的不同:
PRODUCT COUNT
----------------
Apple 4
Beer 3
Bread 3
Notes 2
Car 4
我期望这样的结果:
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
感谢您的帮助,我设置了函数ROW_NUMBER() OVER(PARTITION BY....)
原始表有10000多行。
只需添加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.