COUNT多种类型的同一列

时间:2017-06-10 22:31:18

标签: mysql sql select mariadb

在我当前的查询中:

SELECT COUNT(WC.ID) AS "Regions" 
FROM WHOLE_FEATURES_PDB_CHAINS AS WC 
;

COUNT(WC.ID) AS "Regions"。 但是,我们有多个WC.Type区域可以是1,2,3,4。我需要将每种类型的事件计算到COUNT(WC.ID) AS "Region_1"COUNT(WC.ID) AS "Region_2" ...取决于WC.Type。 有没有办法在一个查询中解决这个问题?我正在研究MySQL IF,但不知道如何将它集成到count函数中。

我需要它在一行中(此处显示的查询已减少,它是一个更大的查询)

SELECT COUNT(WC.ID) AS "Region_1" , COUNT(WC.ID) AS "Region_2" ...

如果有人有兴趣,这是完整的查询:

SELECT PCS.PDB_id, PCS.Chain, PPA.ENSEMBL_start, PPA.ENSEMBL_end, PPA.eValue, PIN.TITLE AS "pdbTitle", COUNT(WC.ID) AS "Regions" 
FROM PDB_Chains AS PCS 
LEFT JOIN WHOLE_FEATURES_PDB_CHAINS AS WC ON WC.PDB_CHAIN_ID = PCS.idPDB_chains, PDB_protein_alignment PPA, PDB_INFOS PIN 
WHERE PCS.idPDB_chains = PPA.idPDB_Chains 
AND PCS.PDB_id = PIN.PDB_ID 
AND PPA.idProteins = (SELECT idProteins from Proteins WHERE ENSEMBL_protein_id = "'+submittedID+'") 
GROUP BY PCS.PDB_id, PCS.Chain ORDER BY PCS.PDB_id;

根据你的答案

,这是工作的解决方案
SELECT PIN.TITLE AS "pdbTitle", COUNT(CASE WHEN WC.STRUCTURAL_FEATURES_ID = 1 then 1 end) AS "PPInterface" , COUNT(CASE WHEN WC.STRUCTURAL_FEATURES_ID = 4 then 1 end) AS "flexibleRegions" 
FROM PDB_Chains AS PCS LEFT JOIN WHOLE_FEATURES_PDB_CHAINS AS WC ON WC.PDB_CHAIN_ID = PCS.idPDB_chains, PDB_protein_alignment PPA, PDB_INFOS PIN 
WHERE PCS.idPDB_chains = PPA.idPDB_Chains 
AND PCS.PDB_id = PIN.PDB_ID 
AND PPA.idProteins = (SELECT idProteins from Proteins WHERE ENSEMBL_protein_id = "ENSP00000256078.4") 
GROUP BY PCS.PDB_id, PCS.Chain ORDER BY PCS.PDB_id;

3 个答案:

答案 0 :(得分:1)

Select
...
...
sum(if WC.ID = 1 then 1 else 0) as Region1,
sum(if WC.ID = 2 then 1 else 0) as Region2,
sum(if WC.ID = 3 then 1 else 0) as Region3,
sum(if WC.ID = 4 then 1 else 0) as Region4

可能做你想做的事。

答案 1 :(得分:1)

您可以在聚合函数中使用case when语句。

试试这个。

计数(WC.type = 1然后1结束时的情况)为region_1,类似地重复另一列。

答案 2 :(得分:0)

您可以GROUP BY使用COUNT来获取所需的结果,例如:

SELECT WC.Type, COUNT(WC.ID) AS "Regions" 
FROM WHOLE_FEATURES_PDB_CHAINS AS WC 
GROUP BY WC.Type;

<强>更新

如果您希望将计数作为每个区域的透视列,则可以编写内部SELECT个查询,例如:

SELECT
 (SELECT COUNT(ID) FROM WHOLE_FEATURES_PDB_CHAINS WHERE type = 1) AS "Region_1",
 (SELECT COUNT(ID) FROM WHOLE_FEATURES_PDB_CHAINS WHERE type = 2) AS "Region_2",
other_column
FROM WHOLE_FEATURES_PDB_CHAINS AS WC
WHERE <some condition>;