在 SQL 服务器 table 中将列转换为行

Transform column into rows in SQL Server table

我有一个查询,我希望其中的某些列显示为行。

查询是

Select * 
From Emp_mon_day 
Where emp_mkey IN (select emp_card_no 
                   from emp_mst 
                   where comp_mkey in (7, 110)) 
  and Year = 2016 and month = 2 
  and Emp_mkey = 2492

返回此输出:

现在,我需要在上述查询的输出中将列 Day1, Day2, Day3 显示为行。

如何实现?

您可以使用如下 UNPIVOT 查询

Select 
comp_mkey, 
fmodule_id,
fdepartment_id,
branch_mkey,
entry_department,
dept_mkey,
mkey,
emp_mkey,
entry_date,
month,
year,
day,
data
from
(select * from Emp_mon_day where emp_mkey IN 
(select emp_card_no from emp_mst where comp_mkey in
(7,110)) and Year = 2016 and month = 2 
and Emp_mkey = 2492) s
unpivot
(
data for day in ([Day1],[Day2]) -- dynamic query can generate all days data
)up

下面是示例测试脚本和输出

create table t(comp_mkey int,mont int,yea int,day1 varchar(10),day2 varchar(10))
insert into t values (2,2,2016,'AB','AC')

Select 
comp_mkey, 
mont,
yea,
day,
data
from
(select * from t) s
unpivot
(
data for day in ([Day1],[Day2]) -- dynamic query can generate all days data
)up
drop table t

输出

如果您需要全天的数据,您可以在此语句中输入所有预期的列

data for day in ([Day1],[Day2], [Day3],[Day4])

更好的方法是将其转换为动态查询并应用一个月预期天数的逻辑

证明交叉应用在这里很有用。

CREATE TABLE [dbo].[emp]
(
    [comp_mkey]    [INT] NULL,
    [mont]         [INT] NULL,
    [year]         [INT] NULL,
    [day1]         [VARCHAR](10) NULL,
    [day2]         [VARCHAR](10) NULL
)

INSERT INTO emp VALUES (2, 2, 2016, 'AB', 'AC')

使用以下 Select 语句

SELECT emp.comp_mkey
   , emp.mont
   , emp.year
   , emp_ext.[Day]
   , emp_ext.Value 
FROM emp
CROSS APPLY 
(
    VALUES('Day1', emp.day1), ('Day2', emp.day2)
)emp_ext([Day], Value)