如何按月计算当前客户摘要并在Power Bi中显示数据

时间:2019-05-20 16:15:54

标签: sql powerbi powerbi-desktop powerbi-datasource

我有一个客户列表,其中包含加入日期和离开日期, 我每个月必须知道有多少人加入,剩下多少人以及摘要

   id   Join        left
   1    01/01/2017  08/03/2017
   2    02/01/2017  25/03/2017
   3    03/01/2017  06/03/2017
   4    04/01/2017  
   5    30/01/2017  
   6    31/01/2017  05/05/2017
   7    01/02/2017  
   8    02/02/2017  22/03/2017
   9    04/02/2017  29/04/2017
  10    05/02/2017  09/04/2017
  11    06/02/2017  08/04/2017
  12    07/02/2017  13/03/2017
  13    04/03/2017  21/05/2017
  14    05/03/2017  
  15    06/03/2017  
  16    07/03/2017  
  17    09/03/2017  
  18    10/03/2017  03/06/2017
  19    11/03/2017  14/04/2017
  20    12/03/2017  31/05/2017
  21    07/04/2017  06/07/2017
  22    08/04/2017  16/06/2017
  23    09/04/2017  10/05/2017
  24    04/03/2018  26/05/2018
  25    24/03/2018  01/06/2018
  26    25/03/2018  15/06/2018
  27    26/03/2018  05/05/2018
  28    27/03/2018  02/07/2018
  29    04/04/2018  
  30    05/04/2018  13/06/2018

这就是预期结果的显示方式

       total left join  month    year
           6    0   6   1     2017
           6    0   6   2   
           3    5   8   3   
          -1    4   3   4   
          -4    4   0   5   
          -2    2   0   6   
          -1    1   0   7   
           3    2   5   3     2018
           2    0   2   4   
           0    0   0   5   
          -3    3   0   6   
          -1    1   0   7

1 个答案:

答案 0 :(得分:1)

如果您的数据库是MySQL或SQL Server,则可以尝试此操作。对于其他数据库,可以使用逻辑/思想。

SELECT
SUM(CASE WHEN Type = 'J' THEN C ELSE 0 END) - SUM(CASE WHEN Type = 'L' THEN C ELSE 0 END) AS [Total],
SUM(CASE WHEN Type = 'L' THEN C ELSE 0 END) AS [left],
SUM(CASE WHEN Type = 'J' THEN C ELSE 0 END) AS [join],
M Month,
Y Year 
FROM
(
    SELECT 'J' AS [Type],
    MONTH(CONVERT(DATETIME, [Join], 103)) M,
    YEAR(CONVERT(DATETIME, [Join], 103)) Y,
    COUNT(ID) C
    FROM customers
    GROUP BY MONTH(CONVERT(DATETIME, [Join], 103)),  YEAR(CONVERT(DATETIME, [Join], 103))

    UNION ALL

    SELECT 'L',
    MONTH(CONVERT(DATETIME, [left], 103)) M,
    YEAR(CONVERT(DATETIME, [left], 103)) Y,
    COUNT(ID) C
    FROM customers
    GROUP BY MONTH(CONVERT(DATETIME, [left], 103)),  YEAR(CONVERT(DATETIME, [left], 103))
)A
WHERE Y IS NOT NULL 
GROUP BY M,Y