如何计算一个数字重复多少次以及一列以上

时间:2016-11-04 20:53:27

标签: mysql sql

示例:

JOHN       | 1   | 6  | 2
PETER      | 1   | 7  | 6
MARK       | 2   | 1  | 6
DIANNA     | 3   | 2  | 1
SPIDERMAN  | 4   | 1  | 6
JAMIE FOXX | 5   | 1  | 6

如何选择3个列中每个列中重复数字的次数

示例:

  • 数字1重复6次。
  • 数字6重复5次。

3 个答案:

答案 0 :(得分:2)

假设您的数字列为c1,c2和c3,表格为t。

{
  "_id": "581cf2597b27281f04e8619e",
  "name": "300",
  "description": "The dvd of the 300 movie",
  "price": 19,
  "seller": "BestDVD",
  "id": "1",
  "quantity": 10,
  "department": "581c783f41d2893b80f3b0ba",
  "category": "581c7f8441d2893b80f3b0c0",
  "visible": true,
  "__v": 0,
  "extra": [
    {
      "id": "1",
      "value": "\".100\"",
      "key": "weight",
      "_id": "581cf2667b27281f04e8619f"
    },
    {
      "id": "1",
      "value": ".250",
      "key": "weight",
      "_id": "581cf2857b27281f04e861a0"
    }
  ]
}

答案 1 :(得分:1)

假设您正在寻找1

一种方法是使用union和sum

select sum(num) from 
(
  select count(*)  as num
  from my_table 
  where col1 = 1
  union all
  select count(*) 
  from my_table 
  where col2 = 1
  union  all
  select count(*) 
  from my_table 
   where col3 = 1 
) t

答案 2 :(得分:0)

SELECT COUNT(CASE WHEN col1 = @number THEN 1 END) + 
       COUNT(CASE WHEN col2 = @number THEN 1 END) +
       COUNT(CASE WHEN col3 = @number THEN 1 END) as repeat
FROM YourTable, (SELECT @number := 1) as parameter