按3个表的层次结构进行计数和分组

时间:2019-06-30 22:24:35

标签: mysql sql

我有3个表的层次结构。

我需要一个查询,该查询返回顶部表中的所有条目,并计算此层次结构底部的条目。

示例:

id_paragraph, sentence_count, word_count, word_count_no_font, word_count_font_present, word_count_no_color, word_count_color_present
1, 10, 100, 20, 80, 25, 75
2, 20, 200, 40, 160, 50, 150

示例输出:

var SVG_NS = 'http://www.w3.org/2000/svg';
var SVG_XLINK = "http://www.w3.org/1999/xlink"
let H = 800, W=500
var R = 9;
//var l = R;
var h = R * Math.sin(Math.PI / 3);
var offset = 1.5 * R;



let i = 0;
for(let y = 0; y<H; y+=h){
i++
let o = (i%2 == 0) ? offset : 0;
for(let x = o; x<W; x+=3*R){
  hex(x,y)
}
}

 function hex(x,y) {
    let angle = map(x, 0, W, 0, 5*Math.PI);
    let c = Math.sin(angle);
    let r = R * .99;
    
    //let r = R * Math.sin(angle)
   
    let points = ""
    for (var a = 0; a < 6; a++) {
      let o = {}
      o.x = x + r * Math.cos(a * Math.PI / 3);
      o.y = y + r * Math.sin(a * Math.PI / 3);
      points+= `${o.x}, ${o.y} `
    } 
   
     let hexagon = drawSVGelmt({points:points},"polygon", svg)
  }




function drawSVGelmt(o,tag, parent) {
  
  let elmt = document.createElementNS(SVG_NS, tag);
  for (let name in o) {
    if (o.hasOwnProperty(name)) {
      elmt.setAttributeNS(null, name, o[name]);
    }
  }
  parent.appendChild(elmt);
  return elmt;
}


function map(n, a, b, _a, _b) {
  let d = b - a;
  let _d = _b - _a;
  let u = _d / d;
  return _a + n * u;
}

第一行的说明: id_paragraph = 1,有10个句子,这些句子中的单词总和= 100,此段落中字体为空的这些单词的总和= 20,此段落中字体不为空的这些单词的总和= 80,此段中这些颜色不为空的句子中的单词总和= 25,此段中这些颜色不为空的句子中的单词总和= 75。

我看到“左联接”和“分组依据”如何为我提供2级深度的解决方案。我尝试扭曲SQL JOIN 3 TABLES WITH COUNT AND GROUP BY CLAUSE,但是显然我什么也没得到。

2 个答案:

答案 0 :(得分:1)

SELECT p.id_paragraph,
(SELECT COUNT(s.id_sentence) FROM sentence s WHERE p.id_paragraph = s.id_paragraph) sentence_count,
(SELECT COUNT(w.id_word) FROM sentence s, word w WHERE s.id_sentence = w.id_sentence AND p.id_paragraph = s.id_paragraph) word_count,
(SELECT COUNT(IFNULL(w.font, 1)) FROM sentence s, word w WHERE s.id_sentence = w.id_sentence AND p.id_paragraph = s.id_paragraph AND w.font IS NULL) word_count_no_font,
(SELECT COUNT(w.font) FROM sentence s, word w WHERE s.id_sentence = w.id_sentence AND p.id_paragraph = s.id_paragraph AND w.font IS NOT NULL) word_count_font_present
...
FROM paragraph p
;

答案 1 :(得分:1)

只需使用count(distinct)

select s.id_paragraph,
       count(distinct s.id_sentence) as num_sentences,
       count(*) as num_words,
       count(w.font) as num_words_with_font,
       sum(w.font is null) as num_words_without_font,
       count(w.color) as num_words_with_color,
       sum(w.color is null) as num_words_without_color
from sentence s join
     word w
     on w.id_sentence = s.id_word
group by s.id_paragraph;