如何计算任意数量的COUNTS的SUM

时间:2012-01-06 19:36:47

标签: mysql count

我想知道是否有可能在一个SQL查询中将每张照片的得分数乘以其得分类型因子的所有产品合计?

示例:

t = total : my aim, the total score for each photo
c_foo = count score type foo = the amount of scores for each photo with the score type name = foo 
c_bar = count score type bar = the amount of scores for each photo with the score type name = bar
m_foo = foo factor
m_bar = bar factor

不同分数类型的数量是任意的。

t = c_foo * m_foo + c_bar * m_bar + … + c_last * m_last

我最初的想法是使用以下表格结构:

到目前为止,我有以下查询:

SELECT p.id, st.name, st.factor, COUNT(*) AS count
FROM s2p_photo p
LEFT JOIN s2p_score s 
LEFT JOIN s2p_score_type st 
GROUP BY p.id, st.name
ORDER BY p.id ASC 

我收到照片的名称,因素和总和,但我无法进行数学计算。

我不知道UNION是否可行。

我的桌子结构好吗?你们中有谁有线索吗?

PS:抱歉,我无法发布图片;请在浏览器中手动打开它们:(

1 个答案:

答案 0 :(得分:2)

不确定我是否明白你的意思,但这是你在寻找什么?

SELECT
  id,
  SUM(factor*count) AS totalscore
FROM (
    SELECT
      p.id AS id,
      st.factor AS factor,
      COUNT(*) AS count 
    FROM
      s2p_photo p 
      LEFT JOIN s2p_score s 
      LEFT JOIN s2p_score_type st 
    GROUP BY p.id, st.name
    ORDER BY p.id ASC
) AS baseview
GROUP BY id