您没有指定您的 RDBMS,但如果您使用的是 MySQL,并且您返回的值数量未知,那么您使用准备好的语句:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(case when month_end = ''',
month_end,
''' then salary end) AS ',
month_end
)
) INTO @sql
FROM yourTable;
SET @sql = CONCAT('SELECT Emp_Id, ', @sql, '
FROM yourtable
GROUP BY Emp_Id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
或者您可以通过类似于@Mahmoud 的答案的静态版本对所有月份进行硬编码
如果您在具有PIVOT
类似于 SQL Server 的功能的 RDBMS 中工作,则可以使用以下内容:
select *
from
(
select emp_id, salary, month_end
from yourtable
) x
pivot
(
max(salary)
for month_end in ([jan], [feb], [mar])
) p
或者使用动态sql:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(month_end)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT emp_id, ' + @cols + ' from
(
select emp_id, salary, month_end
from yourtable
) x
pivot
(
max(salary)
for month_end in (' + @cols + ')
) p '
execute(@query)