多个内部联接添加了额外的值以进行计数

时间:2018-12-12 17:07:06

标签: mysql sql pivot

我正在尝试使用以下多个联接在previous查询中包括来自其他表的结果:

SELECT mid                             as mID,
   round((x.qty_sum / x.qty_count), 5) as qtAVG,
   round(x.qty_stddev, 5)              as qtSTDDEV,
   x.qty_count                         as qtCOUNT,
   round((x.rel_sum / x.rel_count), 5) as relAVG,
   round(x.rel_stddev, 5)              as relSTDDEV,
   x.rel_count                         as relCOUNT,
FROM (SELECT t.mid,
         SUM( mt = 'qt' )   as qty_count,
         SUM(CASE WHEN t_r.mt = 'qt' THEN rt END)  as qty_sum,
         STD(CASE WHEN t_r.mt = 'qt' THEN rt END)  as qty_stddev,
         SUM( t_r.mt = 'rel' ) as rel_count,
         SUM(CASE WHEN t_r.mt = 'rel' THEN rel END) as rel_sum,
         STD(CASE WHEN t_r.mt = 'rel' THEN rel END) as rel_stddev
  FROM t_r r
right join t_m t on t.mid = r.mid
right join m_k m on m.mid = t.mid
right join k_d k on m.kid = k.kid
  GROUP BY t.mid
 ) x;

使用上面的查询,当qty_count111mt的{​​{1}}返回qt而不是62

当我删除连接的这一部分时,我得到了2 * (count of 111 in table m_k)qtCOUNT的期望总和

relCOUNT

我在做什么错,我该如何解决?

数据:

m_k

right join m_k m on m.mid = t.mid
right join k_d k on m.kid = k.kid

k_d

mid  kid
--------
109  2
110  2
110  4
111  1
111  2
111  3

m_d

kid  k_desc
-----------
1    desc1
2    desc2
3    desc3
4    desc4

t_r

mid  col1   col2   col3   col4
-------------------------------
109  val_a  val_d  val_g  val_j
110  val_b  val_e  val_h  val_k
111  val_c  val_f  val_i  val_l

其他达到上述要求的查询也可以。

1 个答案:

答案 0 :(得分:7)

我通过移动

解决了这个问题
right join m_k m on m.mid = t.mid
right join k_d k on m.kid = k.kid

在派生表x之外。最终查询如下:

SELECT mid                             as mID,
   round((x.qty_sum / x.qty_count), 5) as qtAVG,
   round(x.qty_stddev, 5)              as qtSTDDEV,
   x.qty_count                         as qtCOUNT,
   round((x.rel_sum / x.rel_count), 5) as relAVG,
   round(x.rel_stddev, 5)              as relSTDDEV,
   x.rel_count                         as relCOUNT,
FROM (SELECT mid,
         SUM( mt = 'qt' )   as qty_count,
         SUM(CASE WHEN mt = 'qt' THEN rt END)  as qty_sum,
         STD(CASE WHEN mt = 'qt' THEN rt END)  as qty_stddev,
         SUM( mt = 'rel' ) as rel_count,
         SUM(CASE WHEN mt = 'rel' THEN rel END) as rel_sum,
         STD(CASE WHEN mt = 'rel' THEN rel END) as rel_stddev
  FROM t_r r
right join t_m t on t.mid = r.mid
  GROUP BY mid
 ) x
right join m_k m on m.mid = x.mid
right join k_d k on k.kid = m.kid
group by m.mid;