2014-08-27 136 views
0

选择列我有一个PostgreSQL数据库和要显示以下每月和列今年

------------select/display this---------------- 
Year |Jan |Feb |Mar |Apr |May |...|Dec | 
----------------------------------------------- 
2014 |199 |188 |174 |121 |170 |...|200 | 
2013 |160 |140 |160 |170 |160 |...|140 | 
2012 |255 |270 |260 |270 |260 |...|140 | 

和我的表如下所示:

table employeePlans 
----------------------------------------- 
id |month(date)|plannedHours |emplyee_id 
----------------------------------------- 
1 |2012-01-01 |255   | 1 
2 |2012-02-01 |270   | 1 
3 |2012-03-01 |260   | 1 
4 |2012-04-01 |270   | 1 
5 |2012-04-01 |333   | 2 
.. |...  |...   | .. 
9 |2014-01-01 |199   | 1 
10 |2014-02-01 |188   | 1 

每月份是唯一的,当天是本月的第一天(2014-05- )
我实际上使用JPA,如果我可以查询它并将其包装到我的实体类中,并将其显示在我的JavaFX tableview中会更好。
JPA实体类:

@Entity 
@Table(name = "employeeplannedhours", uniqueConstraints 
     = @UniqueConstraint(columnNames = {"month", "employee_id"})) 
public class EmployeePlannedHours implements Serializable { 
private static final long serialVersionUID = 1L; 

//Types are actually JavaFX properties 

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
@Basic(optional = false) 
@Column(name = "id") 
private Integer id; 

@Column(name = "month") 
@Temporal(TemporalType.DATE) 
private Date month; 

@Column(name = "plannedhours") 
private BigDecimal plannedhours; 

@JoinColumn(name = "employee_id", referencedColumnName = "id") 
@ManyToOne 
private Employee employee; 

public EmployeePlannedHours() { 
} 

//Getter and Setters 
} 

我想出现在为止通过旋转和交叉阅读起来很:

SELECT * 
    FROM 
    crosstab('SELECT date_part('year', month)::double as year, 
       //???How can I get plannedhours for every month???, 
       WHERE employee_id = 1     
       GROUP BY year 
       ORDER BY year') 
     As ct(year double, jan numeric, feb numeric, mar numeric, 
      apr numeric, may numeric, jun numeric, jul numeric, 
      aug numeric, sep numeric, oct numeric, nov numeric, 
      dec numeric) 
+0

那你究竟要显示?是否只有一名员工?所有员工的计划时间总和?你是否关注外观(你需要的答案是看你画的方式,这是几个月的列)或只是相同的数据? – Deltharis 2014-08-27 11:51:56

+0

我需要每年的专栏和专栏。我不想要计划好的时间总和。我会标记我想要展示的大胆(这是第一张桌子,一年的列,一月,二月......)。 如果您不了解数据。请在employeePlans表的第9行 - > plannedHours = 199和日期2014年1月的第9行看到,该行应显示在'2014'行中的select语句和'jan'列中的值为'199' 是的我只是为了一名员工 – haisi 2014-08-27 12:03:08

+1

这可能没有帮助,但我在Oracle中会做的是'Group By Emp_ID,Year'。在我的'选择'中,我会创建12列,每个月使用以下代码:'Max(case when to_char(date,'MM')='01'Then PlannedHours End)as Jan'并继续每个月。另外,我会显示'EMP_ID,to_char(date,'YYYY')'我不知道PostGrepSQL,但会想象有类似的功能。如果这有效,我会将其作为答案发布。 – Phillip 2014-08-27 12:45:15

回答

0

我将使用SQL查询,并希望它会帮助你在postgresql

with g 
as 
(select datename(month,[month]) as Month, year(month) as Year,sum(plannedHours) as PlannedHours 
    from employeePlans 
    group by year(month),datename(month,[month]) 
) 
select Year,[Jan],[Feb],[Mar],...[Dec] 
from g 
pivot(sum(PlannedHours) for Month in([Jan],[Feb],....[Dec])) p 

的想法,把月份字段拆分成月份名和叶ar和你在计划时间内由他们分组,那么你应用关键点

为什么要应用该组?因为你的表可能包含同月不同的员工

希望它会帮助你

问候