3

我有一个Employees带有列的表ID, PostID, StartDate, EndDate

样本数据

ID   PostID  StartDate   EndDate
----------------------------------------
1    1       2005/15/08   null      <---Null is still employed
2    2       2006/02/04  2006/08/06
3    1       2004/03/07  9999/12/31 <--- Can also be still Employed
4    2       2008/04/01   null

正确的结果是

Year Post Total
2004 1    1
2005 1    2
2006 1    2
2006 2    1
2007 1    2
2007 2    0
2008 1    2
2008 2    1

注意2007年EmployeeID = 2 PostID = 2已经终止(Endate = 2006/08/06

想要返回特定 PostID 的总和

我用了

SUM(CASE WHEN PostID=1 THEN 1 ELSE 0 END) HPMP, 
  SUM(CASE WHEN PostID=4 THEN 1 ELSE 0 END) HPN,  
  SUM(CASE WHEN PostID=6 THEN 1 ELSE 0 END) HPMW

获取特定的帖子

问题是我需要在 1990 年到 2012 年之间的每一年进行分组

重要提示:我使用的是 SQL Server CE,不能使用脚本或存储过程。

必须是按语句分组的选择。

4

1 回答 1

1

首先,您需要一张年份表。一些 DBMS 有办法即时创建这些。假设一个年份表有一个年份列,并且每年有一行,那么以下应该可以工作:

Select
  y.Year,
  e.PostID,
  Count(*) As Total
From
  Years y
    Inner Join
  Employees e
    On y.Year >= Year(e.StartDate) And (y.Year <= Year(e.EndDate) Or e.EndDate Is Null)
Group By
  y.Year,
  e.PostID
Order By
  1, 2

您可以添加 where 子句来限制年份范围。例如,其中 y.Year >= Year(GetDate()) - 5 并且 y.Year <= Year(GetDate())

如果您也想包含零:

Select
    y.Year,
    p.PostID,
    Count(e.ID) As Total
From
    Years y
        Cross Join
    (Select Distinct PostID From Employees) p
        Left Outer Join
    Employees e
        On 
            y.Year >= Year(e.StartDate) And 
            (y.Year <= Year(e.EndDate) Or e.EndDate Is Null) And
            p.PostID = e.PostID
Group By
    y.Year,
    p.PostID
Order By
    1, 2

如果你有一个 Posts 表,你会使用它而不是 select distinct 位

于 2012-10-31T10:44:53.847 回答