动态列从子表创建

时间:2016-03-13 11:19:48

标签: sql sql-server sql-server-2012

我有两个表给主人和另一个孩子。这描绘如下

主表: enter image description here

和脚本:

CREATE TABLE [dbo].[SET_HRShiftProfile](
    [id] [smallint] NOT NULL,
    [LocationID] [tinyint] NOT NULL,
    [ShiftTypeID] [smallint] NOT NULL,
    [ProfileName] [nvarchar](50) NULL,
    [EmpTypeCode] [nvarchar](10) NOT NULL,
    [IsActive] [bit] NOT NULL,
 CONSTRAINT [PK_HR_ShiftProfile] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

子表: enter image description here 和脚本:

CREATE TABLE [dbo].[SET_HRShiftProfileDetail](
    [id] [int] NOT NULL,
    [LocationID] [tinyint] NOT NULL,
    [ShiftprofileID] [smallint] NOT NULL,
    [ShiftProfTypeCode] [nvarchar](10) NOT NULL,
    [Start] [nvarchar](5) NULL,
    [End] [nvarchar](5) NULL,
    [ToleranceBefore] [nvarchar](5) NULL,
    [ToleranceAfter] [nvarchar](5) NULL,
 CONSTRAINT [PK_SET_HRShiftProfileDetail] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

我需要最终查询结果如下所示,表示所有子表行都是主表的列 enter image description here

任何想法都会让我欣赏。感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

with pivoted as
(
    select LocationID, ShiftprofileID, [IN], [OUT], [Break]
    from (
        select distinct LocationID, ShiftprofileID, [ShiftProfTypeCode]
        from [dbo].[SET_HRShiftProfileDetail]
    ) as t
    pivot (
        count([ShiftProfTypeCode]) for [ShiftProfTypeCode] in ([IN], [OUT], [Break])
    ) as p
)
select p.*
, x.[IN], x.[OUT], x.[Break]
from [dbo].[SET_HRShiftProfile] as p
left join pivoted x on x.ShiftprofileID = p.id
    and x.locationid = p.locationid

结果:

id      LocationID  ShiftTypeID ProfileName EmpTypeCode IsActive    IN  OUT Break
1003    1           1001        Day-Summar  REG         1           1   1   1
1006    1           1005        Say-Winter  REG         1           1   1   0

由于您没有说明您希望进入单元格的数据,因此我在子表中放置了具有此类值(作为列名称)的行数。

希望它能帮助您解决问题

稍后编辑

不使用PIVOT的解决方案:

with pivoted as
(
    select LocationID
    , ShiftprofileID
    , sum(case when [ShiftProfTypeCode] = 'OUT' then 1 else 0 end) [OUT]
    , sum(case when [ShiftProfTypeCode] = 'IN' then 1 else 0 end) [IN]
    , sum(case when [ShiftProfTypeCode] = 'Break' then 1 else 0 end) [Break]
    from [dbo].[SET_HRShiftProfileDetail]
    group by LocationID, ShiftprofileID
)
select p.*
, x.[IN], x.[OUT], x.[Break]
from [dbo].[SET_HRShiftProfile] as p
left join pivoted x on x.ShiftprofileID = p.id
    and x.locationid = p.locationid

结果:

id      LocationID  ShiftTypeID ProfileName EmpTypeCode IsActive    IN  OUT Break
1003    1           1001        Day-Summar  REG         1           1   1   1
1006    1           1005        Say-Winter  REG         1           1   1   0