我有下表:
Code Product
==== =======
AA Prod A
BB Prod B
CC Prod C
CC Prod C1
DD Prod D
我想编写一个查询,该查询接收CC代码并将它们分别转换为CC1和CC2并返回该新数据集。
如何在T-SQL中执行此操作?
答案 0 :(得分:0)
假设您使用的是上面的SQL Server 2005
DECLARE @code TABLE (Code VARCHAR(20), Product VARCHAR(100))
INSERT INTO @code (Code , Product)
VALUES ('AA','Prod A'),('CC','Prod C'),('CC','Prod C1')
;WITH cc AS
(
SELECT Code, COUNT(*) AS CodeCount
FROM @code
GROUP BY Code
)
SELECT
CASE WHEN cc.CodeCount = 1 THEN c.Code
ELSE c.Code + CAST(ROW_NUMBER() OVER ( PARTITION BY c.Code ORDER BY c.Product) AS VARCHAR(10))
END AS Code,
c.Product
FROM @code c
INNER JOIN cc
ON c.Code = cc.Code
答案 1 :(得分:0)
假设你想要
CC Prod C
CC1 Prod C1
CC1 Prod C1
CC2 Prod CX
你可以
;with T as (
select
code,
product,
dense_rank() over (partition by code order by product) as rank
from
thetable
)
select
case rank when 1 then code else code + cast(rank - 1 as varchar(8)) end as code,
product
from
T