0

我有一个表,其中有一个 id 列(跨行重复相同的 id)和列,h1h18列可以包含 wordblob或.parbirdie

我想计算单词出现的次数blobpar或者birdie出现在每个列h1中的次数。h18id

我想最终得到一张像......

id blob par birdie
-- ---- --- ------
1  5    10  3
2  2    15  1
3  8    8   2

我该怎么做?

4

2 回答 2

3

听起来您可能应该在某种程度上规范化您的架构,但就目前情况而言:

SELECT id,
       (h1='blob'  )+(h2='blob'  )+...+(h18='blob'  ) AS blob,
       (h1='par'   )+(h2='par'   )+...+(h18='par'   ) AS par,
       (h1='birdie')+(h2='birdie')+...+(h18='birdie') AS birdie
FROM   my_table
于 2013-01-21T22:40:50.050 回答
0

也许你也可以考虑这个:

select
  id,
  sum(word='blob') as blob,
  sum(word='par') as par,
  sum(word='birdie') as birdie
from
  (select id, h1 word from words union all
   select id, h2 from words union all
   select id, h3 from words union all
   ...) w
group by id

为了使查询更快,您还可以像这样编写子查询:

(select id, h1 word from words where h1 in ('blob', 'par', 'birdie') union all
 select id, h2 from words where h2 in ('blob', 'par', 'birdie') union all
 ...)

但它变得有点难看。我建议您规范化您的数据库。

于 2013-01-21T23:06:26.153 回答