是否可以在一个查询中包含此要求?

时间:2012-02-08 16:34:17

标签: sql

以下是设置:

  • MasterTable有一个booleand HasDetails字段和一个整数Score字段。
  • 如果此字段为true,则DetailsTable包含一个或多个记录,其字段为MasterTableID,其中包含相应MasterTable.AutoID的值。
  • “详细信息”表中的每个子记录都包含整数“频率”值和“分数字段”。

我们想知道按其整数值分组的MasterTable.Score字段的数量,增加了在de DetailsTable.Score字段中找到相同值的次数乘以其频率并除以频率之和它与具有相同DetailsTable.MasterTableID

的记录共享

典型的结果是:

MasterTable

AutoID Score HasDetails
1       100   False
2       ?     True
3       200   False
4       300   False

DetailsTable

MasterTableID Score Frequency
2              200      1
2              300      1

查询结果必须是:

100   1
200   1.5
300   1.5

1 个答案:

答案 0 :(得分:0)

不确定此语法对于您的RDBMS是否正常,但请尝试一下。

SELECT master_count.Score, score_count + COALESCE( weighted_frequency, 0 )
  FROM
  (SELECT Score, COUNT(*) score_count FROM MasterTable GROUP BY Score) master_count
  LEFT OUTER JOIN
  (SELECT Score, SUM(Frequency/sum_frequency) weighted_frequency
     FROM DetailsTable JOIN
         (SELECT MasterTableID, SUM(Frequency) sum_frequency
            FROM DetailsTable GROUP BY MasterTableID) DetailsSum
         ON DetailsTable.MasterTableId = DetailsSum.MasterTableID
     GROUP BY Score) detail_count
  ON detail_count.Score = master_count.Score
  )

这假设,如果详细信息表中的Score值根本不存在于主表中,则您希望忽略它们。如果不是这样,你可以像这样修改它:

SELECT COALESCE( master_count.Score, detail_count.Score ), score_count + COALESCE( weighted_frequency, 0 )
  FROM
  (SELECT Score, COUNT(*) score_count FROM MasterTable GROUP BY Score) master_count
  FULL OUTER JOIN
  (SELECT Score, SUM(Frequency/sum_frequency) weighted_frequency
     FROM DetailsTable JOIN
         (SELECT MasterTableID, SUM(Frequency) sum_frequency
            FROM DetailsTable GROUP BY MasterTableID) DetailsSum
         ON DetailsTable.MasterTableId = DetailsSum.MasterTableID
     GROUP BY Score) detail_count
  ON detail_count.Score = master_count.Score
  )