0

我有一种情况,我正在构建一个派生的数据透视表,然后我希望能够根据各种标准对它进行子选择(实际上是制作一个数据透视表)。

所以......在伪它看起来像这样......

select
   (select sum(score) from derivedTable where username like 'a%') as scoresForANames,
   (select sum(score) from derivedTable where username like 'b%') as scoresForBNames

from
  ( select username, score from gameTable where gameId = 111) derivedTable

请注意,这是一个荒谬的简化示例来说明我所追求的......我根本不需要解决这个例子......我只需要了解 mySQL 中是否有一种概念方式来实现相同的结果。

问题是derivedTable外部选择中的子选择不可见。所以,我很好奇我如何才能达到相同的结果,或者我是否不得不编写子选择来单独考虑所有标准。

4

1 回答 1

1

select您想要表达查询的方式是在子句中根本没有子查询:

select sum(case when username like 'a%' then score end) as scoresForANames,
       sum(case when username like 'b%' then score end) as scoresForBNames
from (select username, score
      from gameTable
      where gameId = 111
     ) derivedTable;

当然,在这种情况下,您根本不需要派生表:

select sum(case when username like 'a%' then score end) as scoresForANames,
       sum(case when username like 'b%' then score end) as scoresForBNames
from gameTable gt
where gameId = 111;
于 2013-07-13T19:01:11.353 回答