多连接列到一列SQL

时间:2018-08-07 08:54:46

标签: sql sql-server concatenation multiple-columns

我们一直在为员工的FIRST IN和LAST OUT做指定的薪资系统格式。 这是FIRST IN和LAST OUT的格式。

  

HS64000701180622I

HS64-前四位数字表示员工编号。

00-代表员工编号与先进先出日期之间的空格

070118-代表首创日期和

0622I-用字母I指示符代表员工的时间,以便系统读取该格式用于FIRSTIN条目数据

  

HS64000701181438O

虽然此格式用于员工的LASTOUT,但显示的格式与FIRSTIN相同,但不同之处在于员工的“ Lastout”时间显示为“ 1438O”,这表示该员工在下午2:38时出局,并且LASTOUT的字母O指示器。

因此,我们有一个查询来显示数据结果。 这是查询:

select  
    CONCAT(UID1FirstName,'00', 
    FORMAT(LogDate, 'MMddyy'),
    REPLACE(CONVERT(varchar, FIRSTIN, 108), ':',''),'I') as FIRSTIN,
    CONCAT(UID1FirstName,'00', 
    FORMAT(LogDate, 'MMddyy'),
    REPLACE(CONVERT(varchar, LASTOUT, 108), ':',''),'O') as LASTOUT from 
(
select 
        CAST(dtDate as DATE) as LogDate,
        MIN(CASE when ReaderName like '%ENTRY%' then FORMAT(dtDate, 'HHmm') END) as FIRSTIN,
        MAX(CASE when ReaderName like '%EXIT%' then FORMAT(dtDate, 'HHmm') END) as LASTOUT, UID1FirstName       
from Log_Transactions
        inner join UserCredentials on UID1 = CredentialId
        inner join UserDefinedFields on HostUserId = UserID
where 
        FieldNo = 1
        and Event = '2000' /*ACCESS GRANTED*/
        and dtDate between '2018-07-01' and '2018-07-03' /*FOR SPECIFIC DATE AND TIME ONLY*/
group by
        CAST(dtDate as DATE), CredentialId, UID1FirstName, UID1LastName, Value
) as DT;

这是查询的结果:

SEE QUERY RESULT HERE

问题是上面显示的查询分为两列。进行查询的最佳方法是仅显示在ONE列中。 像这个样本:

FIRSTIN AND LASTOUT
HS64000701180622I
HS64000701181438O

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

@Jev,为解决您的问题,我将创建一种新格式:

enter image description here

您正在做的是在I:IXXXXI和Last Out甜蜜的O:OXXXXO之间添加“先入为主”时间。

HS64 - The first four digits indicates for the Employee Number.

00 - represents for the space between employee number and date of firstin and lastout

070118 - it represents for the date of firstin and

I0622I - represents for the time in of the employee with an letter I indicator for the system to read that this format is for FIRSTIN entry data

O1438O - will represents for the time in of the employee with an letter O LASTOUT 

您的查询将被修改为:

让我知道怎么回事。

select  
    CONCAT(UID1FirstName,'00', 
    FORMAT(LogDate, 'MMddyy'),
    'I'+REPLACE(CONVERT(varchar, FIRSTIN, 108), ':',''),'I')+
    'O'+REPLACE(CONVERT(varchar, LASTOUT, 108), ':',''),'O') as FIRSTINLASTOUT from 
(
select 
        CAST(dtDate as DATE) as LogDate,
        MIN(CASE when ReaderName like '%ENTRY%' then FORMAT(dtDate, 'HHmm') END) as FIRSTIN,
        MAX(CASE when ReaderName like '%EXIT%' then FORMAT(dtDate, 'HHmm') END) as LASTOUT, UID1FirstName       
from Log_Transactions
        inner join UserCredentials on UID1 = CredentialId
        inner join UserDefinedFields on HostUserId = UserID
where 
        FieldNo = 1
        and Event = '2000' /*ACCESS GRANTED*/
        and dtDate between '2018-07-01' and '2018-07-03' /*FOR SPECIFIC DATE AND TIME ONLY*/
group by
        CAST(dtDate as DATE), CredentialId, UID1FirstName, UID1LastName, Value
) as DT;