Вы можете использовать динамический SQL с поворотом, как показано ниже:
CREATE TABLE TABLE1 (
Code nvarchar(1),
Ind nvarchar(3),
Region nvarchar(10),
Amt decimal(17,7),
Currency nvarchar(3),
Aging nvarchar(6),
[Count] int
)
--create table with data you provided
INSERT INTO TABLE1 VALUES
('X','XYZ','Region1', 16882.96585, 'INR','0-30', 3),
('X','XYZ','Region2', 30831.0445, 'INR','31-60', 3),
('X','XYZ','Region3', 8759.319245, 'INR','61-90', 1),
('X','XYZ','Region4', 39070.18077, 'INR','91-180', 1)
DECLARE @sql nvarchar(max),
@col nvarchar(max)
--here we join all column names we need with aging values
SELECT @col = (
SELECT ','+QUOTENAME([name]+' ('+Aging+')')
FROM TABLE1 t
CROSS JOIN sys.columns c
WHERE [object_id] = OBJECT_ID(N'TABLE1') AND column_id > 2 AND [name] != 'Aging'
FOR XML PATH('')
)
--construction of dynamic query
SELECT @sql = N'
SELECT *
FROM (
SELECT Code,
Ind,
[Columns]+'' (''+Aging+'')'' as [Columns],
[Values]
FROM (
SELECT Code,
Ind,
CAST(Region as nvarchar(max)) Region,
CAST(Amt as nvarchar(max)) Amt,
CAST(Currency as nvarchar(max)) Currency,
CAST(Aging as nvarchar(max)) Aging,
CAST([Count] as nvarchar(max)) [Count],
ROW_NUMBER() OVER (PARTITION BY Code ORDER BY Aging) as RowNum
FROM TABLE1
) as t
UNPIVOT (
[Values] FOR [Columns] IN (Region, Amt, Currency, [Count])
) as unp
) as d
PIVOT (
MAX([Values]) FOR [Columns] IN ('+STUFF(@col,1,1,'')+')
) as pvt'
EXEC sp_executesql @sql
DROP TABLE TABLE1
Вывод:
Code Ind Region (0-30) Amt (0-30) Currency (0-30) Count (0-30) Region (31-60) Amt (31-60) Currency (31-60) Count (31-60) Region (61-90) Amt (61-90) Currency (61-90) Count (61-90) Region (91-180) Amt (91-180) Currency (91-180) Count (91-180)
X XYZ Region1 16882.9658500 INR 3 Region2 30831.0445000 INR 3 Region3 8759.3192450 INR 1 Region4 39070.1807700 INR 1
Надеюсь это поможет.
Если структура запроса не изменится, вы можете PRINT @sql
и затем использовать запрос для своих нужд без динамического SQL.