MYSQL,查询以按标准从组中获取字段中不同值的总和

时间:2014-02-28 05:56:41

标签: mysql sql

表格结构

create table dataList 
(
id int auto_increment primary key ,
field1 char(2),
field2 char(2),
field3 char(2),
field4 char(2),
location_id int ,
sub_locationId int 
)

field1,field2,field3,field4可以有5个不同的值 的 'A,B,C,d,E,F'

目前我只能计算所有值 查询

SELECT COUNT(field1),COUNT(field2),COUNT(field3),COUNT(field4) FROM 
dataList group by location_id, sub_locationId

是否可以在特定位置和子位置的每个字段中获取A,B,C等的数量

预期产出

Location_id sub_locationId  field1|   Count |  field2| Count  | 
-------------------------------------------------------------------
190        |          210 |    A  |     30  |     A  |    20  | 
190        |          210 |    B  |     20  |     B  |     5  | 
190        |          210 |    C  |     10  |     C  |     2  | 
190        |          211 |    A  |     30  |     A  |    24  | 
190        |          211 |    B  |     30  |     B  |    20  |  

示例输入

插入dataList(field1,field2,field3,field4,location_id,sub_locationId) 值( 'A', 'B', 'A', 'B',190210), ( 'B', 'A', 'B', 'A',190210), ( 'C', 'A', 'B', 'A',190210), ( 'A', 'C', 'A', 'C',190210), ( 'B', 'A', 'B', 'B',190210);

2 个答案:

答案 0 :(得分:0)

您应该按所需的所有字段进行分组:

SELECT   location_id, sub_location_id, field1, field2, field3, field4, COUNT(*)
FROM     data_list
GROUP BY location_id, sub_location_id, field1, field2, field3, field4

答案 1 :(得分:0)

如果我理解正确......

您必须执行以下单独的查询:

SELECT COUNT(id)FROM dataList where field1 ='A'group by location_id

SELECT COUNT(id)FROM dataList field2 =由location_id

组成的'A'组

...

或在一个陈述中,我会做子查询,如:

SELECT 
(SELECT COUNT(id) FROM dataList where field1='A' group by location_id) as count_field1,
(SELECT COUNT(id) FROM dataList where field2='A' group by location_id) as count_field2