Postgres到php Array

时间:2014-09-20 14:28:24

标签: php postgresql

我有一张价值表:

CREATE TABLE grade
(id int, name varchar(2), no int);

INSERT INTO grade
(id, name, no)
VALUES
(1, 'A', 7),
(2, 'B', 6),
(3, 'C', 10),
(4, 'D', 12),
(5, 'E', 15),
(6, 'F', 21),
(8, 'B', 16),
(7, 'F', 18),
(9, 'F', 25);

我需要在数组中使用输出..即:

[
  ['range','A','B','F'],
  ['0.00 - 4.41', 1, 1, 0],
  ['4.41 - 8.24', 0 , 1, 1]
  ...
  ...
  ['others', 0, 0, 1]
]

这就是我所要求的(Fiddle):

    select range, array_agg(name) as name, array_agg(count) as count
    from (
        select case
          when no between 0.00 and 4.41 then '0.00 - 4.41'
            when no between 4.41 and 8.24 then '4.41 - 8.24'
            when no between 8.24 and 14.77 then '8.24 - 14.77' 
            when no between 14.77 and 19.35 then '14.77 - 19.35' 
            when no between 19.35 and 23.00 then '19.35 - 23.00'
        else 'Others' end as range, name,  count (*) as count
        from grade
        WHERE name IN ('A','B','F') 
        group by range, name
        order by name
    ) t
    group by range

是否可以仅从db查询获得所需的输出?或者我使用php来迭代?

1 个答案:

答案 0 :(得分:0)

找到了归档结果(Updated Fidddle)的方法:

    select range, sum(a) as a_name, 
                  sum(b) as b_name, 
                  sum(f) as f_name, 
                  sum(count) as total
    from (
        select case
          when no between 0.00 and 4.41 then '0.00 - 4.41'
            when no between 4.41 and 8.24 then '4.41 - 8.24'
            when no between 8.24 and 14.77 then '8.24 - 14.77' 
            when no between 14.77 and 19.35 then '14.77 - 19.35' 
            when no between 19.35 and 23.00 then '19.35 - 23.00'
        else 'Others' end as range, 
                count(name = 'A' OR NULL) as A,
                count(name = 'B' OR NULL) as B,
                count(name = 'F' OR NULL) as F,  
                count (*) as count
        from grade
        WHERE name IN ('A','B','F') 
        group by range, name
        order by name
    ) t
    group by range