2012-07-30 38 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,这可能不是你想要的。