MySQL频率/分布

时间:2014-07-28 15:59:41

标签: mysql sql distribution frequency

我创建了一项调查并将其发送出去。该调查询问用户他们的电子邮件,然后要求他们从包含8种不同选项的下拉菜单中选择他们将吃的餐。 有些人使用相同的电子邮件多次填写调查,但不同的食物选择。

我有一个如下所示的MySQL数据库:

ID | Email | Type of computer

1 | abc@example.com | Pork
2 | abc@example.com | Chicken
3 | gfh@example.com | Pork
4 | xyz@example.com | Beef

我有超过300,000行的这些数据。我已经制作了一个MySQL查询来组织它,所以它看起来像我上面所示。现在,我想算一下有多少人选择猪肉和鸡肉,有多少人选择猪肉和牛肉等等。有什么帮助吗?

更具体地说,我需要确定数据库中有多少人(有多少个独特的电子邮件)与#34; Pork"和#34;鸡肉"或"猪肉"和"牛肉" (等)

1 个答案:

答案 0 :(得分:0)

要计算选择了PorkChicken的人数:

SELECT COUNT(*) AS LikesPorkChicken
FROM MyTable t1
  INNER JOIN Mytable t2 ON t1.Email = t2.Email
WHERE t1.Type ='Pork' 
  AND t2.Type = 'Chicken'

要计算选择了PorkBeef的人数:

SELECT COUNT(*) AS LikesPorkBeef
FROM MyTable t1
  INNER JOIN Mytable t2 ON t1.Email = t2.Email
WHERE t1.Type ='Pork' 
  AND t2.Type = 'Beef'

如果您想在一个查询中使用它,您可以执行以下操作(SQL Fiddle):

SELECT SUM(m.PC) AS PorkChicken, SUM(m.PB) AS PorkBeef, SUM(CB) AS ChickenBeef
FROM 
(
  SELECT 
    CASE WHEN t1.Type = 'Pork' AND t2.Type = 'Chicken' THEN 1 ELSE 0 END AS PC,
    CASE WHEN t1.Type = 'Pork' AND t2.Type = 'Beef' THEN 1 ELSE 0 END AS PB,
    CASE WHEN t1.Type = 'Chicken' AND t2.Type = 'Beef' THEN 1 ELSE 0 END AS CB
  FROM MyTable t1
    INNER JOIN Mytable t2 ON t1.Email = t2.Email 
          AND t1.id <> t2.id
) m;

要确保不计算任何重复项,请使用以下(SQL Fiddle):

SELECT SUM(m.PC) AS PorkChicken, SUM(m.PB) AS PorkBeef, SUM(CB) AS ChickenBeef
FROM 
(
  SELECT 
    CASE WHEN ss.type1 = 'Pork' AND ss.type2 = 'Chicken' THEN 1 ELSE 0 END AS PC,
    CASE WHEN ss.type1 = 'Pork' AND ss.type2 = 'Beef' THEN 1 ELSE 0 END AS PB,
    CASE WHEN ss.type1 = 'Chicken' AND ss.type2 = 'Beef' THEN 1 ELSE 0 END AS CB
  FROM 
  (
    SELECT DISTINCT t1.Email, t1.Type AS type1, t2.Type AS type2
    FROM MyTable t1
    INNER JOIN Mytable t2 ON t1.Email = t2.Email
      AND t1.id <> t2.id
  ) ss
) m;