简体   繁体   English

如何在PostgreSQL中创建交叉表查询

[英]How to create crosstab queries in PostgreSQL

How to use a crosstab function in PostgreSQL, i've tried my own queries but still doesn't work. 如何在PostgreSQL中使用交叉表函数,我已经尝试了自己的查询,但仍然无法正常工作。 I have the following table: 我有下表:

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

and i'd like to create query to return the following crosstab: 并且我想创建查询以返回以下交叉表:

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 

I'm using crosstab() with two parameters like this: 我正在使用带有两个这样的参数的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';

Thanks in advance. 提前致谢。

Simply use CASE WHEN conditional expressions: 只需在条件表达式中使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM