0

我有一张桌子

employeeid WorkedDate Hours
   1        1/1/2013  8
   1        1/2/2013  8
   1        1/3/2013  8
   2        1/4/2013  8
   2        1/5/2013  8
   2        1/6/2013  8
   3        1/7/2013  8
   3        1/8/2013  8
   3        1/9/2013  8

我需要如下输出

   EmployyeCount    WorkedDate    TotalHours 
        1           1/1/2013           72
        0           1/2/2013           0
        0           1/3/2013           0
        1           1/4/2013           0
        0           1/5/2013           0
        0           1/6/2013           0
         1          1/7/2013           0
         0          1/8/2013           0
         0          1/9/2013           0

我不想在这里按月或年分组。有可能像上面那样出去吗?请帮忙

4

2 回答 2

1

很难理解你真正想要什么,但从所需的输出推断,恕我直言,你只需要GROUP BY约会

SELECT COUNT(employeeid) EmployeeCount,
       CAST(WorkedDate AS DATE) WorkedDate,
       SUM(Hours) Hours
  FROM Table1
 WHERE WorkedDate BETWEEN '2013-01-02' AND '2013-01-03'
 GROUP BY CAST(WorkedDate AS DATE)

假设您有这样的样本数据

| EMPLOYEEID | WORKEDDATE | HOURS |
-----------------------------------
|          1 | 2013-01-01 |     8 |
|          1 | 2013-01-02 |     8 |
|          1 | 2013-01-03 |     8 |
|          2 | 2013-01-01 |     8 |
|          2 | 2013-01-02 |     8 |
|          2 | 2013-01-03 |     8 |
|          3 | 2013-01-01 |     8 |
|          3 | 2013-01-02 |     8 |
|          3 | 2013-01-03 |     8 |

此查询将为您提供以下输出

| EMPLOYEECOUNT | WORKEDDATE | HOURS |
--------------------------------------
|             3 | 2013-01-02 |    24 |
|             3 | 2013-01-03 |    24 |

这是一个sqlfiddle 示例

于 2013-03-07T07:22:40.890 回答
0

尝试这个。但是,您可能需要对此进行概括。我不能因为要求不明确。

;with cte1 as
(select min(workeddate) MIN_date from test group by employeeid),

cte2 as 
(select min_date  min_date from cte1
 except
 select min(min_date)from cte1)


select * from 
(select 1 EID,min(min_date) WORKDATE ,(select sum(hours) from test)Hours from cte1

union 

select 1,min_date , 0 from cte2
union
select 0,workeddate,0 from test where workeddate not in
    (select min_date from cte1))a
order by workdate

SQL小提琴

于 2013-03-07T07:54:32.347 回答