0

我有一个名为 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

这里有什么问题吗?谢谢

4

3 回答 3

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

于 2015-12-22T04:57:00.520 回答
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
于 2015-12-22T05:21:36.373 回答
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
于 2015-12-22T06:51:40.300 回答