如何在postgresql中垂直显示我的查询结果?

时间:2016-09-07 09:00:41

标签: sql postgresql pivot crosstab

这是我的SQL查询,我希望这些结果能够垂直显示。我还搜索谷歌这里我发现通过使用\x\g\x打开切换模式,但我不知道在哪里放置该语法。请帮助获得这样的输出:

enter image description here

但是,我的这个查询给出了这样的输出:

enter image description here

                select
            round(
            100.00 *
            (sum(case when "WELL_AGE" <= '5' AND "CONC_ARSC" <= '10' then 1 else 0 end))/(sum(case when "WELL_AGE" <= '5' then 1 else 0 end)),1) conc_arscbelow5_wellageGrp,

            round(
            100.00 *
            (sum(case when "WELL_AGE" >= '6' AND "WELL_AGE" <= '10' AND "CONC_ARSC" <= '10' then 1 else 0 end))/(sum(case when "WELL_AGE" >= '6' AND "WELL_AGE" <= '10' then 1 else 0 end)),1) conc_arscbet6_10wellageGrp,

            round(
            100.00 *
            (sum(case when "WELL_AGE" >= '11' AND "WELL_AGE" <= '15' AND "CONC_ARSC" <= '10' then 1 else 0 end))/(sum(case when "WELL_AGE" >= '11' AND "WELL_AGE" <= '15' then 1 else 0 end)),1) conc_arscbet11_15_wellageGrp,

            round(
            100.00 *
            (sum(case when "WELL_AGE" >= '16' AND "WELL_AGE" <= '30' AND "CONC_ARSC" <= '10' then 1 else 0 end))/(sum(case when "WELL_AGE" >= '16' AND "WELL_AGE" <= '30' then 1 else 0 end)),1) conc_arscbet16_30wellageGrp,

            round(
            100.00 *
            (sum(case when "WELL_AGE" >= '31' AND "WELL_AGE" <= '50' AND "CONC_ARSC" <= '10' then 1 else 0 end))/(sum(case when "WELL_AGE" >= '31' AND "WELL_AGE" <= '50' then 1 else 0 end)),1) conc_arscbet31_50wellageGrp,

            round(
            100.00 *
            (sum(case when "WELL_AGE" > '50' AND  "CONC_ARSC" <= '10' then 1 else 0 end))/(sum(case when "WELL_AGE" > '50' then 1 else 0 end)),1 )conc_arscabove50_wellageGrp


            from public."Arsenic_Test";

2 个答案:

答案 0 :(得分:0)

我希望这符合您的要求。

使用 hstore

with t as (SELECT '80.13' aS "0-5", '80.7' AS "6-10", '81.6' AS "11-15", '84.27' AS "16-30", '84.04' AS "31-50", '85.33' AS ">50")
SELECT * 
FROM (SELECT (each(hstore(t))).* FROM t) AS tmp (well_age, below10_conc_arsc_wells)

将t替换为你的桌子。 使用 json

with t as (SELECT '80.13' aS "0-5", '80.7' AS "6-10", '81.6' AS "11-15", '84.27' AS "16-30", '84.04' AS "31-50", '85.33' AS ">50")
SELECT * 
FROM (SELECT (json_each_text(row_to_json(t))).* FROM t) AS tmp (well_age, below10_conc_arsc_wells)

答案 1 :(得分:0)

使用range type分组:

with r (r,s) as ( values
    (int4range(null,5,'[]'), '0 - 5'),
    (int4range(6,10,'[]'), '6 - 10'),
    (int4range(11,15,'[]'), '11 - 15'),
    (int4range(16,30,'[]'), '16 - 30'),
    (int4range(31,50,'[]'), '31 - 50'),
    (int4range(50,null,'(]'), '>50')
)
select s, 100* count("CONC_ARSC" <= '10' or null) / count(*)
from
    public."Arsenic_Test"
    inner join
    r on "WELL_AGE" <@ r
group by s;