如何将Excel操作应用于SQL Server查询?

问题描述 投票:0回答:3

我当前正在使用SSMS 2008。

我想使用SSMS完成操作,并在Excel屏幕快照中进行了描述。

我有两个表,一个表对雇员开始工作的时间有一个正数,而一个表对雇员休假的时间有一个负数。我正在寻找一列显示每小时员工人数的列。感谢您对此事的帮助,谢谢,enter image description here

sql sql-server
3个回答
0
投票

SUM OVER的替代方法是自连接,其聚合值较低或相等。

样本数据:

CREATE TABLE TestEmployeeRegistration (
  [Date] DATE, 
  [Time] TIME, 
  [Employees] INT NOT NULL DEFAULT 0,
  PRIMARY KEY ([Date], [Time])
);

INSERT INTO TestEmployeeRegistration
([Date], [Time], [Employees]) VALUES
('2019-11-01', '08:00', 2),
('2019-11-01', '09:00', 5),
('2019-11-01', '10:00', 3),
('2019-11-01', '12:00',-5),
('2019-11-01', '13:00', 2),
('2019-11-01', '14:00',-5);

查询:

SELECT t.[Date], t.[Time], t.[Employees]
, SUM(t2.[Employees]) AS [Total available]
FROM [TestEmployeeRegistration] t
JOIN [TestEmployeeRegistration] t2 
  ON t2.[Date] = t.[Date]
 AND t2.[Time] <= t.[Time]
GROUP BY t.[Date], t.[Time], t.[Employees]
ORDER BY t.[Date], t.[Time];

[当使用SUM的窗口功能时,然后根据“日期”建议分区。

SELECT *
, SUM([Employees]) OVER (PARTITION BY [Date] ORDER BY [Time]) AS [Total available]
FROM [TestEmployeeRegistration]
ORDER BY [Date], [Time];

关于妊娠期here的测试


1
投票

正在运行,可以使用windowed SUM来实现:

SELECT *, SUM(Employee) OVER(ORDER BY [Date], [Time]) as Total_available
FROM tab
ORDER BY [Date], [Time];

0
投票

SQL Fiddle

MS SQL Server 2017架构设置

CREATE TABLE MyTable (Dates Date,Times Time, EmployeesAvailable int)
INSERT INTO MyTable (Dates,Times,EmployeesAvailable) VALUES('2019-11-01','08:00',2)
INSERT INTO MyTable (Dates,Times,EmployeesAvailable) VALUES('2019-11-01','09:00',5)
INSERT INTO MyTable (Dates,Times,EmployeesAvailable) VALUES('2019-11-01','10:00',3)
INSERT INTO MyTable (Dates,Times,EmployeesAvailable) VALUES('2019-11-01','12:00',-5)
INSERT INTO MyTable (Dates,Times,EmployeesAvailable) VALUES('2019-11-01','13:00',2)
INSERT INTO MyTable (Dates,Times,EmployeesAvailable) VALUES('2019-11-01','14:00',-5)

查询1

SELECT Dates,Times,EmployeesAvailable,
           SUM(EmployeesAvailable) OVER(ORDER BY Dates,Times) AS 'Total Available'
FROM MyTable

Results

|      Dates |            Times | EmployeesAvailable | Total Available |
|------------|------------------|--------------------|-----------------|
| 2019-11-01 | 08:00:00.0000000 |                  2 |               2 |
| 2019-11-01 | 09:00:00.0000000 |                  5 |               7 |
| 2019-11-01 | 10:00:00.0000000 |                  3 |              10 |
| 2019-11-01 | 12:00:00.0000000 |                 -5 |               5 |
| 2019-11-01 | 13:00:00.0000000 |                  2 |               7 |
| 2019-11-01 | 14:00:00.0000000 |                 -5 |               2 |
© www.soinside.com 2019 - 2024. All rights reserved.