简体   繁体   English

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

[英]How to Calculate Current Customer Summary by Month and Display Data in Power Bi

I have a list of customers with a date of joining and a date of leaving, I have to know each month by year how many joined and how many left and what the summary 我有一个客户列表,其中包含加入日期和离开日期,我必须逐年知道每年有多少加入者,剩下多少以及摘要

   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

And that is how the desired result appears 这就是预期结果的显示方式

       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

You can try this if your database is either MySQL or SQL server. 如果您的数据库是MySQL或SQL Server,则可以尝试此操作。 For other databases, you can use the logic/idea. 对于其他数据库,可以使用逻辑/思想。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM