如何在PostgreSQL

时间:2016-05-14 03:16:13

标签: sql database postgresql

如何在PostgreSQL中使用交叉表功能,我已经尝试了自己的查询,但仍然无法正常工作。我有下表:

sampling_point  time_sampling   entero  sampling_type
  wall             06:53          50    Environment
  floor            09:21          50    Environment
  wall             09:22          50    Environment
  wall             09:23          50    Environment
  floor            06:52          10    Environment
  wall             06:53          50    Environment
  floor            06:32          10    Environment
  wall             06:33          50    Environment
  floor            06:32          50    Environment
  wall             06:33          50    Environment
  floor            06:52          50    Environment
  floor            09:22          50    Environment

并且我想创建查询以返回以下交叉表:

sampling_point  time_sampling   entero_floor   entero_wall  
  wall             06:53                          50       
  wall             09:22                          50     
  wall             09:23                          50       
  wall             06:53                          50       
  wall             06:33                          50       
  wall             06:33                          50     
  floor            09:21          50                     
  floor            06:52          10                     
  floor            06:32          10                     
  floor            06:32          50
  floor            06:52          50
  floor            09:22          50 

我使用 crosstab()和两个参数,如下所示:

SELECT * FROM crosstab
    (
        'SELECT c.sampling_date, c.sampling_point, c.time_sampling, c.ha_entero 
         FROM (select t066dtl.*, t066hdr.* from tblfrmintqad066dtl t066dtl 
                      JOIN tblfrmintqad066hdr t066hdr ON t066hdr.headerid = t066dtl.headerid AND t066dtl.status= 1 ) c
         ORDER  BY 1,2',
            $$VALUES ('floor'::text),('wall'::text)$$
    )
     AS ct (sampling_point varchar, floor varchar, wall varchar) c.sampling_date = '2016-05-12';

提前致谢。

1 个答案:

答案 0 :(得分:0)

只需使用CASE WHEN条件表达式:

SELECT sampling_point, time_sampling,
       CASE WHEN sampling_point = 'floor' THEN entero ELSE NULL END AS entero_floor,   
       CASE WHEN sampling_point = 'wall' THEN entero ELSE NULL END AS entero_wall
FROM SourceTable
ORDER BY sampling_point DESC;