SQL更改数据格式的最小值和最大值

时间:2015-08-07 01:25:32

标签: sql sql-server sql-server-2008

我有以这种格式出现的出勤数据:

EmployeeId |    Date    |   Time   |
--------------------------------------
        1  | 01/01/2015 | 14:01:35 |
        2  | 01/01/2015 | 13:00:00 |
        1  | 01/01/2015 | 17:35:37 |
        1  | 01/01/2015 | 18:01:35 |
        2  | 01/01/2015 | 19:14:12 |
        1  | 01/02/2015 | 14:21:42 |
        2  | 01/02/2015 | 15:12:03 |
        1  | 01/02/2015 | 15:42:20 |

我需要以下格式的数据:

EmployeeId |    Date    | FirstTime | LastTime |
--------------------------------------------------
        1  | 01/01/2015 | 14:01:35  | 18:01:35 |
        2  | 01/01/2015 | 13:00:00  | 19:14:12 |
        1  | 01/02/2015 | 14:21:42  | 15:42:20 |
        2  | 01/02/2015 | 15:12:03  | 15:12:03 | 

FirstTimeMin(Time)的{​​{1}},而date/employeelasttime的{​​{1}}。我已经删除了自动增量PK以简化。

我无法理解如何做到这一点。我在想max(time)可能是要走的路,但我无法用它来达到理想的效果。你能帮我解决一下这个问题吗?

2 个答案:

答案 0 :(得分:7)

select employeeid, date, min(time) as firsttime, max(time) as lasttime
from tablename
group by employeeid, date

您可以按employeeid分组,并选择给定日期的最短和最长时间。

答案 1 :(得分:1)

You can use Pivot, here is example:

CREATE TABLE Product(Cust VARCHAR(25), Product VARCHAR(20), QTY INT)
GO
-- Inserting Data into Table
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','VEG',2)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','SODA',6)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','MILK',1)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','BEER',12)
INSERT INTO Product(Cust, Product, QTY)
VALUES('FRED','MILK',3)
INSERT INTO Product(Cust, Product, QTY)
VALUES('FRED','BEER',24)
INSERT INTO Product(Cust, Product, QTY)
VALUES('KATE','VEG',3)
GO
-- Selecting and checking entires in table
SELECT *
FROM Product
GO
-- Pivot Table ordered by PRODUCT
SELECT PRODUCT, FRED, KATE
FROM (
SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT (SUM(QTY) FOR CUST IN (FRED, KATE)) AS pvt
ORDER BY PRODUCT
GO
-- Pivot Table ordered by CUST
SELECT CUST, VEG, SODA, MILK, BEER, CHIPS
FROM (
SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT (SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt
ORDER BY CUST
GO

Relative link: link