2017-06-05 3 views
0

Ich habe eine Abfrage wie folgt aus:Add Monat/Jahr zu jeder zurückgegebene Zeile Postgres SQL

select location, subItem1, item2, SUM(sub.intervalEnd - sub.intervalStart +1) as days 

from (select 
    location, item1,item2, 
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart, 
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd, 
    case when item1 = 'APPLE' then item1 else 'ORANGE' end as subItem1 
from myTable 

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01') 
    OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31') 
group by item1, item2, location, effective_start_date, effective_end_date 
    )sub 
    group by location, subItem1, item2 

, die eine Tabelle wie folgt zurückgibt:

Location | subItem1 | subItem2 | days 
"LOC1","APPLE","thisItem2","31" 
"LOC2","APPLE","thisItem2","31" 
"LOC3","ORANGE","thisItem2","31" 
"LOC4","APPLE","thisItem2","62" 
"LOC5","APPLE","thisItem2","31" 
"LOC6","APPLE","thisItem2","62" 

Aber was ich brauche, ist der Monat hinzufügen/Jahr für jede Zeile wie folgt:

"05/2017","LOC1","APPLE","thisItem2","31" 
"05/2017","LOC2","APPLE","thisItem2","31" 
"05/2017","LOC3","ORANGE","thisItem2","31" 
"05/2017","LOC4","APPLE","thisItem2","62" 
"05/2017","LOC5","APPLE","thisItem2","31" 
"05/2017","LOC6","APPLE","thisItem2","62" 

Irgendwelche Ideen? Ich schaute auf die Extrakt-Funktion, aber es gibt mir nur entweder Monat oder Jahr. Aber ich brauche beides.

+0

@danihp Ja ich mit dieser Idee gespielt habe, das einzige Problem ist, ist es mir zusätzliche Zeilen für jeden Standort gibt. Ich kann nur eine Zeile pro Standort haben ... – Daryn

Antwort

-1

Wahrscheinlich war eine sehr noob Frage. Aber ich lerne nur sql und schaffte es, es herauszufinden. Die Antwort war wirklich einfach, einfach in eine andere select-Anweisung einfügen. Keine Ahnung, ob dies der beste Weg, um darüber zu gehen - aber es funktioniert:

select location, subItem1, item2, days, theMonth 

from (
select location, subItem1, item2, SUM(sub.intervalEnd - sub.intervalStart +1) as days 

from (select 
    location, item1,item2, 
    case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart, 
    case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd, 
    case when item1 = 'APPLE' then item1 else 'ORANGE' end as subItem1 
from myTable 

where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01') 
    OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31') 
group by item1, item2, location, effective_start_date, effective_end_date 
    )sub 
    group by location, subItem1, item2 

)t 

group by location, month, item1, item2 
order by location 
Verwandte Themen