我有一个父表SalType
,在该表中Saltype_name
是列名。另一个与StaffSal
具有外键关系的表SalType
。在StaffSal
中,我输入了每个SalType_name的值
表结构就像这样
SalType --table1
SS_id SalType_name
1 Basic
2 HRA
3 DA
StaffSal --table2
SV_id SS_id SV_value U_id
2 1 15000 11
3 2 0.1 11
4 3 0.75 11
5 1 10000 12
6 2 0.01 12
7 3 0.5 12
我需要像这样显示
U_id Basic HRA DA ...
11 15000 .1 .75
12 10000 .01 .5
有人可以帮忙吗?
答案 0 :(得分:2)
有几种方法可以将数据从行转换为列。
SQL Server有一个PIVOT
函数,可用于旋转数据。
如果要将有限数量的值转换为列,则可以对查询进行硬编码:
select u_id, Basic, HRA, DA
from
(
select t.saltype_name,
s.u_id,
s.sv_value
from saltype t
left join staffsal s
on t.ss_id = s.ss_id
) src
pivot
(
max(sv_value)
for saltype_name in (Basic, HRA, DA)
) piv;
但是如果你有一个未知数量的值,那么你将需要实现动态SQL来生成结果:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(SalType_name)
from SalType
group by SS_id, SalType_name
order by SS_id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT u_id, ' + @cols + '
from
(
select t.saltype_name,
s.u_id,
s.sv_value
from saltype t
left join staffsal s
on t.ss_id = s.ss_id
) x
pivot
(
max(sv_value)
for saltype_name in (' + @cols + ')
) p '
execute(@query)
两个查询都给出了结果:
| U_ID | BASIC | HRA | DA |
------------------------------
| 11 | 15000 | 0.1 | 0.75 |
| 12 | 10000 | 0.01 | 0.5 |
答案 1 :(得分:1)
sql server中的Pivot可用于获取上述结果。
SELECT * FROM
(SELECT
SV_value,
SalType_name,
U_id
FROM
StaffSal
INNER JOIN SalType
ON StaffSal.SS_id= SalType.SS_id) AS SalaryDetails
PIVOT (SUM(SV_value) FOR SalType_name IN (HRA,Basic,DA)) AS PVT