2016-10-28 1 views
2

Ich versuche, den Count DISTINCT-Teil der Abfrage unten zu ändern, da die aktuelle Abfrage die WINDOW-Definition nicht unterstützt. Was ist der einfachste Weg, um diese Berechnung mit PostgreSQL durchzuführen? Vielen Dank.Count Distinct mit PostgreSQL

SELECT transaction_date, brand, Description, Amount, newval 
into temp.table 
FROM (SELECT transaction_date, brand, Description, Amount, 
     (Amount/count(DISTINCT unique_mem_id) over (partition by to_char(transaction_date, 'YYYY-MM'),brand 
     )) as newval 
    FROM source.table 
) 
WHERE DESCRIPTION iLIKE '%Criteria%'; 
+1

können Sie Probe Eingang und Ausgang – Nikhil

+0

Ich versuche wirklich zu fragen, wie man Führen Sie eine Count Distinct-Berechnung mit PostgreSQL durch. – ZJAY

+0

'Partition von to_char (transaction_date, 'YYYY-MM')' Sie müssen nicht in char konvertieren, verwenden Sie einfach date_trunc: 'Partition von date_trunc ('Monat', transaction_date)' – wildplasser

Antwort

0

Durch den Einsatz-Fall scheint es besser, den Code zu teilen.

Erstellen Sie eine Tabelle month_brand auf die folgende Abfrage basiert:

select  to_char(transaction_date, 'YYYY-MM') as yyyymm 
      ,brand 
      ,count (distinct unique_mem_id)   as count_distinct_unique_mem_id 

from  source.table 

group by yyyymm 
      ,brand 
; 

Registriert month_brand mit Ihrem Quelltabelle:

select  t.transaction_date, t.brand, t.Description, t.Amount, t.Amount/m.count_distinct_unique_mem_id as newval 

from     source.table as t 

      join  month_brand  as m 

      on   m.yyyymm = to_char(t.transaction_date, 'YYYY-MM')  

where  t.description ilike '%Criteria%' 
; 

Statt count(distinct ...), 2-Phasen-Lösung:

  1. gibt Zeilennummern an die dupliziert unique_mem_id
  2. Zählung nur die unique_mem_id mit row_number = 1

select * 

into  temp.table 

from (SELECT transaction_date, brand, Description, Amount, 
       (Amount/count(case rn when 1 then unique_mem_id end) over (partition by to_char(transaction_date, 'YYYY-MM'),brand)) as newval 

     FROM (SELECT  transaction_date, brand, Description, Amount,unique_mem_id 
          row_numner() over (partition by to_char(transaction_date, 'YYYY-MM'),brand,unique_mem_id) as rn 

       FROM  source.table 
       ) 
     ) 

WHERE DESCRIPTION iLIKE '%Criteria%' 
; 
+0

Hallo @ ZJAY, Bitte sehen Sie sich an die Lösung. –

+0

Lösung zurückgegeben ERROR: Spalte "unique_mem_id" existiert nicht in derived_table1 – ZJAY

+0

@ZJAY, fixed ... –