我有一个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- 01 )
我实际上使用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
}
到目前为止,通过阅读pivot和交叉表,我想到的是:
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 :(得分: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
这个想法是,将月份字段拆分为月份名称和年份,然后按计划小时将它们分组,然后应用数据透视
为什么要申请这个小组?因为您的表可能包含同月不同的员工
希望它会帮助你
问候