从表格中的同一列获取日期为“从日期”和“到日期”

时间:2015-07-30 11:59:10

标签: sql postgresql postgresql-9.3

我的表格中有timestamp字段'changed_date'。我想将'changed_date'改为'from_date'和'to_date'。也就是说,对于每一行,'from_date'值应来自前一行'changed_date'值。 例如:

enter image description here

我希望将结果与'project_id'分组。我想得到:

first row as:         null - 2015-07-02
second row as:  2015-07-02 - 2015-07-15
third row as:   2015-07-15 - 2015-07-28 

2 个答案:

答案 0 :(得分:2)

您需要一个窗口功能来有效地执行此操作:

public CustomListAdapter(Context context,List<Song> results) { 
mList = results;
Song ALL = new Song();
ALL.setTitle("ALL");
mList.add(0,ALL); 
mInflater = LayoutInflater.from(context); 
}

输出为SELECT id, percentage, vat, service_tax, labor_welfare, daterange(lag(changed_date) OVER (PARTITION BY project_id ORDER BY changed_date)::date, changed_date::date, '()') AS changed_date_range, project_id FROM my_table ORDER BY project_id, changed_date; ,看起来像'(2015-07-02,2015-07-15)'。如果您更喜欢字符串格式,可以将daterange短语更改为:

daterange(...)

或者你可以只有两列:

(to_char(lag(changed_date) OVER (PARTITION BY project_id ORDER BY changed_date), 'YYYY-MM-DD') ||
' - ' || to_char(changed_date, 'YYYY-MM-DD') AS changed_date_range

答案 1 :(得分:0)

不要低估你想要的东西..

你在寻找像

这样的东西吗?
SELECT DATEADD(day,-1, changed_date) AS from_date, changed_date AS to_date FROM YOUR_TABLE;