我有工会查询,我试图在每个行类型中添加单独的seq编号查询返回:
我想添加这样的seq行号:
如何在sql或hanna DB中使用这种行号?
答案 0 :(得分:0)
SELECT
CONCAT(
MainType,
' (',
ROW_NUMBER() OVER(PARTITION BY MainType ORDER BY MainType),
')'
) as MainType,
CONCAT(
LineType,
' (',
ROW_NUMBER() OVER(PARTITION BY MainType, LineType ORDER BY MainType, LineType),
')'
) as LineType
FROM
table
答案 1 :(得分:0)
我不知道Hanna Db但是如果你使用SQL服务器,你可以尝试下面看看这是否是你想要的
Create Table #Table
(
MainType varchar(4),
LineType varchar(6)
)
Insert Into #Table
Values
('A', 'Aa'),
('A', 'Ab'),
('A', 'Aa'),
('A', 'Ac'),
('A', 'Ab'),
('B', 'Aa'),
('B', 'Ab'),
('B', 'Ab'),
('B', 'Ac'),
('B', 'Ab'),
('C', 'Aa'),
('C', 'Ac'),
('C', 'Aa')
Select *,
DENSE_RANK() OVER (Order By MainType) as MainTypeRank,
ROW_NUMBER() OVER (Partition By MainType, LineType Order By LineType) as LineTypeRank
From #Table
Order by MainType
答案 2 :(得分:0)
尝试使用此代码获取您的确切结果
Create Table #TempTable
(
MainType varchar(4),
LineType varchar(6)
)
Insert Into #TempTable
Values
('A', 'Aa'),
('A', 'Ab'),
('A', 'Aa'),
('A', 'Ac'),
('A', 'Ab'),
('B', 'Aa'),
('B', 'Ab'),
('B', 'Ab'),
('B', 'Ac'),
('B', 'Ab'),
('C', 'Aa'),
('C', 'Ac'),
('C', 'Aa')
以上是样本数据。获得结果的脚本
SELECT CASE
WHEN Lag(maintyperank)
OVER(
ORDER BY maintyperank) = maintyperank THEN ''
ELSE maintyperank
END AS MainType,
linetyperank
FROM (SELECT *,
maintype + '('
+ Cast(Dense_rank()OVER(ORDER BY maintype) AS VARCHAR(5))
+ ')' AS MainTypeRank,
linetype + '('
+ Cast(Row_number() OVER (partition BY maintype, linetype ORDER
BY
linetype)AS
VARCHAR(5))
+ ')' AS LineTypeRank
FROM #TempTable)Dt
结果
MainType linetyperank
-------------------------
A(1) Aa(1)
Aa(2)
Ab(1)
Ab(2)
Ac(1)
B(2) Aa(1)
Ab(1)
Ab(2)
Ab(3)
Ac(1)
C(3) Aa(1)
Aa(2)
Ac(1)