我有一个独特的情况。我很抱歉这个问题太天真或不清楚。
我有一个表(称为Table1),如下所示:
Student First Name | Last name | ID | Test Name | Result
Anthony | Davis | 12353 | abc_1_1 | Pass
Chris | Tucker | 23412 | abc_1_3 | Fail
Anthony | Davis | 12355 | abc_2_4 | Fail
Anthony | Davis | 12356 | abc_2_1 | Pass
Anthony | Davis | 12635 | abc_1-5 | Fail
Anthony | Davis | 12375 | abc_2_3 | Pass
Anthony | Davis | 12935 | abc_1_8 | Fail
Chris | Tucker | 23341 | abc_1_2 | Pass
Chris | Tucker | 23541 | abc_2_3 | Pass
Chris | Tucker | 23431 | abc_1_4 | Fail
Chris | Tucker | 21341 | abc_2_1 | Pass
Chris | Tucker | 32341 | abc_1_6 | Fail
David | Steel | 34352 | abc_2_3 | Fail
David | Steel | 34352 | abc_1_2 | Pass
David | Steel | 34352 | abc_2_4 | Fail
David | Steel | 34352 | abc_1_1 | Pass
David | Steel | 34352 | abc_1_7 | Fail
我想要实现的表(table2)就像:
Name | Test Type | Pass | Fail
AnthonyDavis | Type_1 | 1 | 2
AnthonyDavis | Type_2 | 2 | 1
ChrisTucker | Type_1 | 1 | 2
ChrisTucker | Type_1 | 1 | 2
DavidSteel | Type_1 | 2 | 1
DavidSteel | Type_1 | 0 | 1
是否有可能实现这是SQL?
primary key for Table2 is (Name,Test Type)
或者是否更容易让临时表收集所需的数据,然后将其传输到Table2?
答案 0 :(得分:4)
假设TestType
值基于TestName
的前五个字符,那么您应该能够使用与此类似的东西来选择数据:
-- insert into Table2 (name, TestType, Pass, Fail)
select concat(StudentFirstName, Lastname) name,
case left(TestName, 5)
when 'abc_1' then 'Type_1'
when 'abc_2' then 'Type_2'
end testtype,
sum(case when result = 'Pass' then 1 else 0 end) Pass,
sum(case when result = 'Fail' then 1 else 0 end) Fail
from Table1
group by concat(StudentFirstName, Lastname),
case left(TestName, 5)
when 'abc_1' then 'Type_1'
when 'abc_2' then 'Type_2'
end;
见SQL Fiddle with Demo。获得所需格式的数据后,即可轻松将其插入Table2
。
如果我对你如何获得TestType
的假设不正确,那么请提供有关如何确定这一点的详细信息。
注意,MySQL允许SELECT中的别名用于GROUP BY:
-- insert into Table2 (name, TestType, Pass, Fail)
select concat(StudentFirstName, Lastname) name,
case left(TestName, 5)
when 'abc_1' then 'Type_1'
when 'abc_2' then 'Type_2'
end testtype,
sum(case when result = 'Pass' then 1 else 0 end) Pass,
sum(case when result = 'Fail' then 1 else 0 end) Fail
from Table1
group by name, testtype;