我对SQL比较陌生,并写了很多不同的观点。
我被要求使用SQL Server的时钟为我们的月工资单创建一份报告。
目前SQL格式化:
Date | Name | Clock In | Clock Out
-----------+------+-------------------------+------------------------
01/02/2018 | Name | 2018-02-01 07:55:08.563 | 2018-02-01 10:21:42.183
01/02/2018 | Name | 2018-02-01 10:32:37.153 | 2018-02-01 13:12:33.773
01/02/2018 | Name | 2018-02-01 13:33:10.123 | 2018-02-01 15:04:16.880
但我希望这样:
Date | Name | Clock In | Clock Out | Clock In | Clock Out | Clock In | Clock Out
--
01/02/2018 | Name | 2018-02-01 07:55:08.563 | 2018-02-01 10:21:42.183 | 2018-02-01 10:32:37.153 | 2018-02-01 13:12:33.773 | 2018-02-01 13:33:10.123 | 2018-02-01 15:04:16.880
我目前使用以下公式在Excel中工作:
{=INDEX(Payroll_Clockings[Start Time], SMALL(IF(1 = ((--($A9=Payroll_Clockings[Date Value])) * (--($J$4=Payroll_Clockings[Name]))), ROW(Payroll_Clockings[Start Time]) -1, ""), COLUMN() -1))}
但作为一个数组公式,当有50多条记录时,这可能需要很长时间才能刷新。
因此,通过SQL重新安排事情是理想的。
我正在使用的SQL视图是:
SELECT TOP (100) PERCENT
CONVERT(VARCHAR(19), ShopFloor.EmployeeActivity.StartEvent, 103) AS Date,
Admin.Employee.FirstName + ' ' + Admin.Employee.Surname AS Name,
ShopFloor.EmployeeActivity.StartEvent AS [Start Time],
ShopFloor.EmployeeActivity.FinishEvent AS [Finish Time],
ShopFloor.EmployeeActivity.ClockNumber AS [Clock No.]
FROM
ShopFloor.EmployeeActivity
LEFT OUTER JOIN
Admin.Employee ON ShopFloor.EmployeeActivity.ClockNumber = Admin.Employee.ClockNumber
WHERE
(ShopFloor.EmployeeActivity.StartEvent BETWEEN GETDATE() - 180 AND GETDATE())
AND (NOT (ShopFloor.EmployeeActivity.ClockNumber IN (100, 10090, 10000, 777, 999, 10001, 10098, 10002)))
AND (ShopFloor.EmployeeActivity.ActivityTypeCode = 1)
ORDER BY
Date, Name, [Start Time]
希望这是有道理的,任何帮助都会受到赞赏!
看完这里后:SQL Server - PIVOT - two columns into rows
这似乎是正确的想法,但是他们只在5行上工作,我目前的数据大约有10,000行...会有解决方法吗?
由于
答案 0 :(得分:0)
如果您知道每个员工的最大登录/注销组合数,这样的事情就会有效。如果没有,则必须使用动态sql生成数据透视表。尝试一下,让我知道它对你有用:
select a.date, a.name, a.[1],b.[1],a.[2],b.[2],a.[3],b.[3] from (
select date, name, max([1])[1],max([2])[2],max([3])[3] from(
select *, row_number() over(partition by date, name order by date)b from #temp) a
pivot(max(clockin) for b in ([1],[2],[3]))c
group by date, name)a
left join
(
select date, name, max([1])[1],max([2])[2],max([3])[3] from(
select *, row_number() over(partition by date, name order by date)b from #temp) a
pivot(max(clockout) for b in ([1],[2],[3]))c
group by date, name)
b on a.date=b.date and a.name=b.name