SQL查询以相应和不同的方式对值进行分组

时间:2016-08-15 01:57:06

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

美好的一天专家,

我在数据库中有一个原始数据,它看起来像这样(简化)。表名:tblSchedule

Employee    Date         Tenants
Employee 1  1-Jan-16     McDonalds
Employee 1  1-Jan-16     Burger King
Employee 1  2-Jan-16     Jamba Juice
Employee 2  2-Jan-16     Kenny Rogers
Employee 2  3-Jan-16     Starbucks

我需要做的是按Employee相应地对数据进行分组,并根据可用记录设置日期列。我已经开始在SQL中使用此查询(我使用了静态日期,但在我当前的代码中,日期是根据用户输入动态加载的)

    Select Employee, Date, Tenant 
    Into #Query1
    From tblSchedule


    Select Employee,
    CASE  WHEN (Date= '01/01/2016') THEN Tenant  ELSE  Null END AS [01/01/2016]
    ,CASE  WHEN (Date= '01/01/2016')  THEN Tenant  ELSE  Null END AS [01/02/2016]
    ,CASE  WHEN (Date = '01/03/2016')  THEN Tenant  ELSE  Null END AS [01/03/2016]
    From #Query1

它会产生这种输出

Employee     1-Jan-16       2-Jan-16      3-Jan-16
Employee 1   Mcdonalds     null           null
             Burger King   null           null
             null          Jamba Juice    null
Employee 2   null          Kenny Rogers   null
             null          null           Starbucks

作为输出我需要实现的是正确的分组,其中像这样删除空值

Employee      1-Jan-16      2-Jan-16        3-Jan-16
Employee 1    Mcdonalds     Jamba Juice     null
              Burger King   null            null
Employee 2    null          Kenny Rogers    Starbucks

我已经开始使用此代码,但仍然无法生成所需的输出

  Select Employee,
  CASE  WHEN (Date= '01/01/2016') THEN Tenant  ELSE  Null END AS [01/01/2016]
  ,CASE  WHEN (Date= '01/01/2016')  THEN Tenant  ELSE  Null END AS [01/02/2016]
  ,CASE  WHEN (Date = '01/03/2016')  THEN Tenant  ELSE  Null END AS [01/03/2016]
  Into #Query2
    From #Query1


    Select Employee, 
    Max[01/01/2016] as [01/01/2016],
    Max[01/02/2016] as [01/02/2016],
    Max[01/03/2016] as [01/03/2016],
    From #Query2
    Group By Employee

它几乎获得了所需的输出,但在01/01/2016只得到一个值(最大值)

希望得到您的积极反馈。感谢

1 个答案:

答案 0 :(得分:2)

执行此操作的一种简单方法是使用按行号分组的条件聚合:

e.g。

SELECT Employee
     , MAX(CASE WHEN Date = '01/01/2016' THEN Tenants END)
     , MAX(CASE WHEN Date = '01/02/2016' THEN Tenants END)
     , MAX(CASE WHEN Date = '01/03/2016' THEN Tenants END)
FROM (
    SELECT *
         , ROW_NUMBER() OVER (PARTITION BY Employee, Date ORDER BY Date) RN
    FROM myTable) T
GROUP BY Employee, RN
ORDER BY Employee, RN;