2012-07-30 41 views
-1

,我有以下格式的數據結合我行的PostgeSQL:如何使用Python2.7

|------------------------| 
| Product | Color | Year | 
|------------------------| 
| Ball | Blue | 1999 | 
| Ball | Blue | 2000 | 
| Ball | Blue | 2001 | 
| Stick | Green | 1984 | 
| Stick | Green | 1985 | 
|------------------------| 

我如何可以轉換到這個如下:

|-----------------------------| 
| Product | Color | Year Range| 
|-----------------------------| 
| Ball | Blue | 1999-2001 | 
| Stick | Green | 1984-1985 | 
|-----------------------------| 

的數據是在PostgreSQL表,並且包含需要以這種方式整合的187,000多行。我如何使用Python 2.7來處理這個問題?

回答

2

數據位於PostgreSQL表中,包含187,000+行,其中 迫切需要以這種方式進行整合。

它可能迫切需要整合這樣的報告,但它幾乎肯定不會需要加以鞏固這種方式進行存儲。在這裏輕輕一步。

您可以用GROUP BY子句以大致的格式獲取數據。 (我用「product_color_years」作爲表名。)

select product, color, min(year), max(year) 
from product_color_years 
group by product, color 

爲鞏固年進入一列,使用連接運算符。

select product, color, min(year) || '-' || max(year) year_range 
from product_color_years 
group by product, color 

這僅只要

  • 沒有任何差距在一年範圍內,或
  • 有差距,但你不在乎。

如果有,你想看到報道這樣的差距:

product color year_range 
-- 
Ball  Blue 1999-2001 
Ball  Blue 2003-2005 
Stick Mauve 2000, 2010 

,那麼你可能會更好過使用報告作家。 (例如,谷歌「python報告」。)上面的SQL將報告這些藍色球爲Ball Blue 1999-2005,這可能不是你想要的。