使用来自多个表

时间:2016-09-02 17:30:13

标签: sql sql-server

我有三个表:tblEmpDatatblEmpAttDevicetblEmpAttDeviceUsers

tblEmpData拥有所有员工,tblEmpAttDevice拥有所有考勤设备,tblEmpAttDeviceUsers有员工参加特定设备ID。

表架构:

tblEmpData

    [ID] [int] IDENTITY(1,1) NOT NULL,
    [EmpID] [int] NOT NULL,
    [EmpName] [varchar](255) NOT NULL,
    [EmpCivilID] [varchar](100) NULL,
    [EmpCivilIDExp] [date] NULL,
    [EmpHourWageKD] [varchar](20) NULL,
    [EmpPhone] [varchar](50) NULL,
    [EmpDOB] [date] NULL,
    [EmpJoinDate] [date] NULL,
    [EmpType] [varchar](10) NULL,
    [EmpEmail] [varchar](255) NULL,
    [EmpAddress] [varchar](255) NULL,
    [EmpPassword] [varchar](255) NULL,
    [EmpEnabled] [int] NULL,
    [EmpDeviceID] [int] NULL,
    [EmpCompanyHired] [int] NOT NULL DEFAULT ((1)),
    [EmpVenueID] [int] NULL,
    [EmpStatusID] [int] NULL,
    [DriversLicenseNo] [varchar](100) NULL,
    [DriversLicenseExpiry] [date] NULL

tblEmpAttDevice

    [DeviceID] [int] NOT NULL,
    [DeviceName] [varchar](50) NULL,
    [DeviceIP] [varchar](50) NOT NULL,
    [DevicePort] [int] NOT NULL,
    [VenueID] [int] NOT NULL,
    [EventID] [int] NOT NULL,
    [LastImport] [datetime] NULL,
    [ACTIVE_FLAG] [bit] NULL

tblEmpAttDeviceUsers

    [EmpID] [int] NULL,
    [DeviceID] [int] NULL,
    [lastseen] [datetime] NULL,
    [action] [int] NULL

我想构建SQL查询以生成以下视图。

enter image description here

如果tblEmpAttDevice中存在任何员工ID,那么tblEmpAttDeviceUsers表的所有行都会成为列并创建矩阵,然后是其他N.

我处于封锁阶段,我该怎么做呢。请帮我在SQL Server中构建一个查询。感谢

1 个答案:

答案 0 :(得分:1)

在这种情况下,你可以使用 PIVOT

尝试使用以下脚本。

SELECT EmpID,EmpName,Emp_Enabled,Employment_status
   ,CASE WHEN [Kuwait Soft]>0 THEN 'Y' ELSE 'N' END [Kuwait Soft]
   ,CASE WHEN [Avenues]>0 THEN 'Y' ELSE 'N' END [Avenues]
   ,CASE WHEN[360 Mall]>0 THEN 'Y' ELSE 'N' END [360 Mall]
   ,CASE WHEN [AlHarma]>0 THEN 'Y' ELSE 'N' END [AlHarma]
   ,CASE WHEN [Sidra]>0 THEN 'Y' ELSE 'N' END [Sidra]
   ,CASE WHEN[Symphony]>0 THEN 'Y' ELSE 'N' END [Symphony]

FROM
(SELECT a.EmpID, a.EmpID EmployeeID,a.EmpName
       ,a.EmpEnabled Emp_Enabled,a.EmpStatusID Employment_status,c.DeviceName
FROM tblEmpData a
 JOIN tblEmpAttDeviceUsers b on a.EmpID=b.EmpID
 JOIN tblEmpAttDevice c on b.DeviceID=c.DeviceID) src
 PIVOT (MAX([EmployeeID]) for [DeviceName]  IN ([Kuwait Soft],[Avenues],[360 Mall],[AlHarma],[Sidra],[Symphony]))as Res;

输出:

enter image description here