以下是设置:
我们想知道按其整数值分组的MasterTable.Score字段的数量,增加了在de DetailsTable.Score字段中找到相同值的次数乘以其频率并除以频率之和它与具有相同DetailsTable.MasterTableID
的记录共享典型的结果是:
AutoID Score HasDetails 1 100 False 2 ? True 3 200 False 4 300 False
MasterTableID Score Frequency 2 200 1 2 300 1
查询结果必须是:
100 1 200 1.5 300 1.5
答案 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
)