NoyRaz
NoyRaz

Reputation: 80

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

Upvotes: 0

Views: 43

Answers (1)

mkRabbani
mkRabbani

Reputation: 16908

You can try this if your database is either MySQL or 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

Upvotes: 1

Related Questions