Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我想在sql中将分类值拆分为不同的字段_Sql_Postgresql_Pivot - Fatal编程技术网

我想在sql中将分类值拆分为不同的字段

我想在sql中将分类值拆分为不同的字段,sql,postgresql,pivot,Sql,Postgresql,Pivot,数据是这样的- 州、区、分类两个字段-明确和可疑。 我想得到格式表2中的数据 表-1 State,DC, cat2 ASSAM KAMRUP CLEAR ASSAM KAMRUP CLEAR ASSAM KAMRUP SUSPECT ASSAM KAMRUP CLEAR ASSAM Cachar CLEAR ASSAM Cachar CLEAR BIHAR Buxar SUSPECT BIHAR Buxar CLEAR BIHAR Buxar CLEAR BIHAR Buxar

数据是这样的- 州、区、分类两个字段-明确和可疑。 我想得到格式表2中的数据

表-1

State,DC,     cat2
ASSAM KAMRUP CLEAR
ASSAM KAMRUP CLEAR
ASSAM KAMRUP SUSPECT
ASSAM KAMRUP CLEAR
ASSAM Cachar CLEAR
ASSAM Cachar CLEAR
BIHAR Buxar  SUSPECT
BIHAR Buxar  CLEAR
BIHAR Buxar  CLEAR
BIHAR Buxar  SUSPECT
BIHAR Buxar  CLEAR
BIHAR Buxar  SUSPECT
BIHAR Buxar  CLEAR
我想要这样的东西- 表-2


在Postgres中,您可以使用过滤聚合:

select state, dc, 
       count(*) filter (where cat2 = 'CLEAR') as clear, 
       count(*) filter (where cat2 = 'SUSPECT') as suspect
from the_table
group by state, dc;

在Postgres中,您可以使用过滤聚合:

select state, dc, 
       count(*) filter (where cat2 = 'CLEAR') as clear, 
       count(*) filter (where cat2 = 'SUSPECT') as suspect
from the_table
group by state, dc;
您也可以将sum与case语句一起使用

select
  state,
  DC,
  sum(case when cat2 = 'CLEAR' then 1 else 0 end) as clear,
  sum(case when cat2 = 'SUSPECT' then 1 else 0 end) as suspect
from yourTable
group by 
  state,
  DC 
您也可以将sum与case语句一起使用

select
  state,
  DC,
  sum(case when cat2 = 'CLEAR' then 1 else 0 end) as clear,
  sum(case when cat2 = 'SUSPECT' then 1 else 0 end) as suspect
from yourTable
group by 
  state,
  DC