Search code examples
sqlarrayspostgresqldistinct

How can I select distinct inside an array based on date?


I would like to display the value (distinctly) from my database (PostgreSQL) here is my code:

SELECT distinct t.*, round(SUM(percentage)OVER (order by agentname rows between unbounded preceding and current row),3) AS cumulative
FROM (
  SELECT 
    a.*,
    COUNT(*) AS frequency,
   round(COUNT(*) * 100.00 / SUM(COUNT(*)) OVER (),4) AS percentage
  FROM 
      (select agentname,inputdate, unnest(array[ WSalamPembuka,WKonfirmasiNamaCust, WVerifikasiData,WKemampuanBertanya,WProductKnowledge,WSolusi,WAlternativeSolusi,WSistemPelaporan,WEmpati,WResponsif,WRamahSopan,WPercayaDiri,WHoldCall,WOfferHelp,WPenutup]) as weakness                        
                from call )as a 
                  WHERE a.agentname like '%wendra%' and a.weakness is not null and a.weakness !='' and a.inputdate between '01/12/2015' and  '08/01/2016'
                  group by a.agentname,a.weakness,a.inputdate
                  order by frequency desc
                ) AS t
                ORDER BY frequency DESC 

        
 

And the result I got is: enter image description here

As you can see I got duplicate data here. I want it to be like:

enter image description here

Any trick to solve this?


Solution

  • The reason for your getting duplicates is because you're grouping by the input date:

    group by a.agentname,a.weakness,a.inputdate
    

    Just remove the inputdate from your group by clause (and from the outer select clause), and you'll get the desired result (notice my changes by commenting out inputdate):

    SELECT distinct t.*, round(SUM(percentage)OVER (order by agentname rows between unbounded preceding and current row),3) AS cumulative
    FROM (
      SELECT 
        a.*,
        COUNT(*) AS frequency,
       round(COUNT(*) * 100.00 / SUM(COUNT(*)) OVER (),4) AS percentage
      FROM 
          (select agentname,inputdate, unnest(array[ WSalamPembuka,WKonfirmasiNamaCust, WVerifikasiData,WKemampuanBertanya,WProductKnowledge,WSolusi,WAlternativeSolusi,WSistemPelaporan,WEmpati,WResponsif,WRamahSopan,WPercayaDiri,WHoldCall,WOfferHelp,WPenutup]) as weakness                        
                    from call )as a 
                      WHERE a.agentname like '%wendra%' and a.weakness is not null and a.weakness !='' and a.inputdate between '01/12/2015' and  '08/01/2016'
                      group by a.agentname,a.weakness/*,a.inputdate*/
                      order by frequency desc
                    ) AS t
                    ORDER BY frequency DESC