不同的SQL不能与UNNEST和ARRAY一起使用

时间:2015-12-22 04:44:22

标签: arrays postgresql distinct unnest string-function

我有一个名为Data的数据库,如下所示:

ID | Name | Weakness1 | Weakness2 | Weakness3
_____________________________________________
 1 |  A   |    W1     |     W2    |    Null
 2 |  B   |    NULL   |     W2    |    W3
 3 |  C   |    W1     |     NULL  |    NULL
 4 |  A   |    W1     |     W2    |    W3
 5 |  A   |    W1     |     NULL  |    NULL

我喜欢查询,因此可以显示如下:

 Name |    Weakness     | Frequency
___________________________________
  A   |   W1            |   3
  A   |   W2            |   2
  A   |   W3            |   1

请注意,同名可以具有不同的ID。到目前为止,我尝试了代码:

 Select DISTINCT Name, 
 UNNEST(ARRAY[weakness1,weakness2,weakness3] as Weakness,
 UNNESR(ARRAY[count(weakness1),count(weakness2),count(weakness2)])
 from data 
 where agentname like '%A%'
 GROUP by agentname,weakness1,weakness2,weakness3

我还显示了一个NULL行。在'where'之后不允许COUNT(Weakness1)> 0并且我得到的弱点是多余的,尽管我已经添加了'DISTINCT'

所以它显示如下:

 Name |    Weakness     | Frequency
___________________________________
  A   |   W1            |   1
  A   |                 |   0
  A   |   W3            |   1
  A   |   W1            |   2
  A   |   W2            |   1
  A   |   W2            |   1

这里有什么问题?谢谢

3 个答案:

答案 0 :(得分:1)

你能尝试这样的事吗?

with data as (
  select name, weakness1 as weakness from tablename
  union all
  select name, weakness2 as weakness from tablename
  union all
  select name, weakness3 as weakness from tablename
)
select name, weakness, count(*)
from data
where name like '%A%' and weakness is not null
group by name, weakness

结果

| name | weakness | count |
|------|----------|-------|
|    A |       W1 |     3 |
|    A |       W3 |     1 |
|    A |       W2 |     2 |

示例:http://sqlfiddle.com/#!15/7e4aa/3

替代方法:

select name, weakness, count(*) from (
  select name, unnest(array[weakness1, weakness2, weakness3]) as weakness
  from tablename
) t
where name like '%A%' and weakness is not null
group by name, weakness;

示例:http://sqlfiddle.com/#!15/7e4aa/6

答案 1 :(得分:0)

SELECT NAME
    ,unnest(regexp_split_to_array(concat_ws(',', weak1, weak2, weak3), ',')) weakness
    ,count(unnest(regexp_split_to_array(concat_ws(',', weak1, weak2, weak3), ','))) frequency
FROM dat
WHERE NAME = 'A' -- or use WHERE NAME like '%A%'
GROUP BY 2,1

答案 2 :(得分:0)

找到这个

   select Name,Weakness1 as weakness,count(Weakness1) from data
     where name ='A' group by name,weakness1

     Union all

     select Name,Weakness2 as weakness,count(Weakness2) from data
     where name ='A' and Weakness2 ='W2' group by name,weakness2

     union all

     select Name,Weakness3 as weakness,count(Weakness3) from data
     where name ='A' and Weakness3 ='W3' group by name,weakness3