为每个返回的行postgres sql添加月/年

时间:2017-06-05 12:35:26

标签: sql postgresql

我有这样的查询:

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

返回如下表格:

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"

但我需要的是将Month / Year添加到每一行,如下所示:

"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"

有什么想法吗?我查看了提取功能,但它只给了我一个月或一年。但我需要两者。

1 个答案:

答案 0 :(得分:-1)

可能是一个非常的菜鸟问题。但我只是学习SQL并设法解决它。答案真的很简单,只需将其包装在另一个选择语句中即可。 Dunno,如果这是最好的方式 - 但它的确有效:

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