如何在sql server中获取给定日期范围的Distinct值

时间:2013-03-07 06:43:34

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

我有一张桌子

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

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

2 个答案:

答案 0 :(得分: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 example

答案 1 :(得分: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 Fiddle