0

我在这里有一个独特的情况。我很抱歉这个问题太天真或不清楚。

我有一个看起来像这样的表(称为 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 是否更容易?

4

1 回答 1

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 允许在 GROUP BY 中使用来自 SELECT 的别名:

-- 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;
于 2013-05-09T15:00:04.807 回答