SQL查询 - 将数据值转换为属性到另一个表中。

时间:2016-01-28 11:29:36

标签: sql

我正在制作一份报告,而我却陷入了制定查询的困境。在很多连接之后,我从多个表中提取以下数据。

ID        TYPE    RATING
-----     ----    ------
ID_R1     A       1
ID_R1     B       3
ID_R2     A       2
ID_R2     B       1
ID_R3     A       4
ID_R3     B       4
ID_R4     A       2
ID_R4     B       3
ID_R5     A       2
ID_R5     B       3

实际发生的是Every ID will have a Rating for Type A & B所以我需要做的是将上述内容转换为以下内容

ID       Type_A_Rating    Type_B_Rating
-----    -------------    -------------
ID_R1    1                3
ID_R2    3                1
ID_R3    4                4
ID_R4    2                3
ID_R5    2                3

我认为小组和不同的技术,但到目前为止我无法提出解决方案。需要帮助F1! F1!

p.s仅用于记录我的最终游戏获得(A,B)组合的计数

Type_A_Rating    Type_B_Rating    Count
-------------    -------------    -----
1                1                0
1                2                0
1                3                1
1                4                0
2                1                0
2                2                0
2                3                2
2                4                0
3                1                1
3                2                0
3                3                0
3                4                0
4                1                0
4                2                0
4                3                0
4                4                1

从这里可以看出,在我获得上述数据之前,任何形式为GROUP BY AND条件的简单OR都不够。我可以使用两个中间/临时表,在一个中获取带有ID的Type_A_Rating,然后在第二个带有ID的Type_B_Rating中,然后在另一个中使用ID,但是没有更好的方法。

1 个答案:

答案 0 :(得分:4)

这应该作为SQL引擎无关的解决方案(前提是每个ID只有一行具有类型A,每个ID都有一行类型B):

select
  TA.ID,
  TA.RATING as Type_A_Rating,
  TB.RATING as Type_B_Rating
from
(select ID, RATING
 from T where TYPE = 'A') as TA
inner join
(select ID, RATING
  from T where TYPE = 'B') as TB
on TA.ID = TB.ID

相关SQL小提琴:http://sqlfiddle.com/#!9/7e6fd9/2

替代(更简单)解决方案:

select
  ID,
  sum(case when TYPE = 'A' then RATING else 0 end) as Type_A_Rating,
  sum(case when TYPE = 'B' then RATING else 0 end) as Type_B_Rating
from
  T
group by
  ID

小提琴:http://sqlfiddle.com/#!9/7e6fd9/3

编辑:

以上是正确的,但两者都可以简化:

select TA.ID, TA.RATING as Type_A_Rating, TB.RATING as Type_B_Rating
from T TA join
     T TB
     on TA.ID = TB.ID AND A.type = 'A' and B.type = 'B';

并且(因为当没有匹配时我更喜欢NULL

select ID,
       max(case when TYPE = 'A' then RATING end) as Type_A_Rating,
       max(case when TYPE = 'B' then RATING end) as Type_B_Rating
from T
group by ID