有条件的rowcount

时间:2011-09-08 13:25:35

标签: sql sql-server

Emplid        FunctionId          Count 

1-------      2 
1 ------      3   ----------      1 
1 ------      4   ----------      2 
1  ------     4
1 ------      5 ----------        3 
1  ------     6     ----------    4 
1   ------    3      ----------   5 
2    ------   3 
2   ------    3 
2   ------    1      ----------   1 
2    ------   2     ----------    2 

H& R正在寻找一种衡量公司灵活性/流动性的措施。

当Employee从作业/功能更改时,FunctionID存储在DWH empl dim中。请参阅上面的示例,该表如何显示(6000个员工记录也有很多突变)。

所以我只有在员工要做其他事情时才需要计算(另一项功能)。 上面的例子向您展示了计数输出应该如何。

如何使用T-SqL或SSIS包(foreach循环?)

1 个答案:

答案 0 :(得分:1)

声明

对于给定的测试脚本,SQL Server遵循Employee CTE中的插入顺序,但要注意保证每次都这样做。

您必须在ROW_NUMBER语句中提供除EmplId之外的其他排序顺序。

SQL语句

;WITH EmployeeRank AS (
  SELECT  EmplId
          , FunctionID
          , rn = ROW_NUMBER() OVER (ORDER BY EmplId)
  FROM    Employee
)
SELECT  er1.EmplID, COUNT(*)
FROM    EmployeeRank er1
        INNER JOIN EmployeeRank er2 
          ON  er2.Emplid = er1.Emplid
              AND er2.rn = er1.rn + 1
              AND er2.FunctionId <> er1.FunctionId
GROUP BY
        er1.EmplID

测试脚本

;WITH Employee(Emplid, FunctionId) AS (
            SELECT 1, 2 
  UNION ALL SELECT 1, 3 --1        
  UNION ALL SELECT 1, 4 --2         
  UNION ALL SELECT 1, 4
  UNION ALL SELECT 1, 5 --3          
  UNION ALL SELECT 1, 6 --4
  UNION ALL SELECT 1, 3 --5      
  UNION ALL SELECT 2, 3 --1
  UNION ALL SELECT 2, 3 
  UNION ALL SELECT 2, 1 --2         
  UNION ALL SELECT 2, 2 --3         
)
, EmployeeRank AS (
  SELECT  EmplId
          , FunctionID
          , rn = ROW_NUMBER() OVER (ORDER BY EmplId)
  FROM    Employee
)
SELECT  er1.EmplID, COUNT(*)
FROM    EmployeeRank er1
        INNER JOIN EmployeeRank er2 
          ON  er2.Emplid = er1.Emplid
              AND er2.rn = er1.rn + 1
              AND er2.FunctionId <> er1.FunctionId
GROUP BY
        er1.EmplID