반응형
하나의 쿼리(MySQL)에서 여러 조건에 대한 다중 COUNT()
다음과 같은 질문이 있습니다.
SELECT COUNT(*) FROM t_table WHERE color = 'YELLOW';
SELECT COUNT(*) FROM t_table WHERE color = 'BLUE';
SELECT COUNT(*) FROM t_table WHERE color = 'RED';
이러한 결과를 하나의 쿼리로 얻을 수 있는 방법이 있습니까?
결과를 한 행에 표시하려면 다음을 사용할 수 있습니다.
SELECT
SUM(IF(color = 'YELLOW', 1, 0)) AS YELLOW,
SUM(IF(color = 'BLUE', 1, 0)) AS BLUE,
SUM(IF(color = 'RED', 1, 0)) AS RED
FROM t_table
SELECT color, COUNT(*) FROM t_table GROUP BY color
SELECT 'yellow' as color ,COUNT(*) FROM t_table WHERE color = 'YELLOW'
union
SELECT 'blue' , COUNT(*) FROM t_table WHERE color = 'BLUE'
union
SELECT 'red',COUNT(*) FROM t_table WHERE color = 'RED';
아니면
select color, count(*) from table where color in ('red', 'blue', 'yellow') group by 1
서브쿼리를 사용해서 할 수 있습니다.
SELECT(
SELECT COUNT(*) FROM t_table WHERE color = 'YELLOW',
SELECT COUNT(*) FROM t_table WHERE color = 'BLUE',
SELECT COUNT(*) FROM t_table WHERE color = 'RED'
);
이것도 당신에게 효과가 있을 거라고 생각합니다.
select count(*) as anc,(select count(*) from Patient where sex='F')as
patientF,(select count(*) from Patient where sex='M') as patientM from anc
이와 같은 관련 테이블을 선택하고 셀 수도 있습니다.
select count(*) as anc,(select count(*) from Patient where
Patient.Id=anc.PatientId)as patientF,(select count(*) from Patient where
sex='M') as patientM from anc
조금 늦었지만 Sinte의 답변을 받음
[case] 쿼리 요구 사항 - 여러 개의 개수가 있는 여러 항목 이름
select
t1.person_name
,(
select count(person_id) from persons where sex='F' and person_id=t1.person_id
)as quantity_M
,(
select count(person_id) from persons where sex_id='M' and person_id=t1.person_id
) as quantity_F
from persons as t1
group by t1.person_name
order by t1.person_name;
제 대답은 이렇습니다.
SELECT sm_med_t_servicios.id as identidad, count(sm_adm_t_admision.id) as cantidad ,
SUM(IF(sm_adm_t_admision.atendido = 'S', 1, 0)) AS atendidos,
SUM(IF(sm_adm_t_admision.atendido = 'N', 1, 0)) AS por_ver
FROM sm_med_t_servicios
LEFT JOIN sm_adm_t_admision ON sm_med_t_servicios.id = sm_adm_t_admision.sm_med_t_servicios_id
WHERE sm_med_t_servicios.m_empresas_id = '2'
GROUP BY sm_med_t_servicios.id
도움이 되길 바랍니다.
언급URL : https://stackoverflow.com/questions/19046812/multiple-count-for-multiple-conditions-in-one-query-mysql
반응형
'programing' 카테고리의 다른 글
| node.js 스택 오류에 10개 이상의 행이 있습니까? (0) | 2023.09.21 |
|---|---|
| PHP AJAX 12017 헤더 호출 시 오류(위치:) (0) | 2023.09.21 |
| C/C++에서 두 개의 '주요' (0) | 2023.09.21 |
| 어떻게 하면 중앙에 유연한 기둥이 하나 있는 고정 폭 기둥 두 개를 가질 수 있습니까? (0) | 2023.09.21 |
| UIAapplication.registerForRemoteNotifications()는 기본 스레드에서만 호출해야 합니다. (0) | 2023.09.21 |