MySQL导致分组查询中相同字段值的计数

时间:2013-11-14 18:03:35

标签: mysql sql

很难用文字解释,但我试图将数据按类型分组并加入另一个表来获得结果。

这是我的SqlFiddle示例。

以下是一个示例数据:

(链接表)[id,type,created]

(1, 1, '2013-01-01')
(2, 1, '2013-01-02')
(3, 2, '2013-01-03')
(4, 4, '2013-01-04')

(信息表)[id,link_id,info_type,tally,tick]

(1, 1,1,10,15)
(1, 2,2,20,17)
(1, 3,1,12,14)
(1, 4,2,18,21)

我想要的结果是:[type_a,type_b,tally,tick]

(1, 1, 30, 32)
(1, 0, 12, 14)
(0, 1, 18, 21)

我得到的结果

(2, 2, 30, 32)
(1, 1, 12, 14)
(1, 1, 18, 21)

这是我正在使用的查询

SELECT 
    COUNT(i.info_type) as type_a,
    COUNT(i.info_type) as type_b,
    SUM(i.tally) as tally,
    SUM(i.tick) as tick
FROM link l
JOIN info i ON (l.id = i.link_id)
WHERE l.created BETWEEN '2013-01-01' AND '2014-01-01'
GROUP BY l.type

总结一下,我想获取日期范围内的所有链接,按link.type分组 然后返回等于1的info_type的计数作为type_a并将等于2作为type_b 和tally和tick的总和是正确的。它只是type_a和type_b结果 那是错的。

2 个答案:

答案 0 :(得分:1)

SELECT 
    SUM(i.info_type = 1) AS type_a,
    SUM(i.info_type = 2) AS type_b,
    SUM(i.tally) AS tally,
    SUM(i.tick) AS tick
FROM link l
JOIN info i ON l.id = i.link_id
WHERE l.created BETWEEN '2013-01-01' AND '2014-01-01'
GROUP BY l.type ;

SUM(i.info_type = 1)是一个MySQL成语。可读性更强的SQL代码是:

SELECT 
    COUNT(CASE WHEN i.info_type = 1 THEN 1 ELSE NULL END) AS type_a,
    COUNT(CASE WHEN i.info_type = 2 THEN 1 ELSE NULL END) AS type_b,
    SUM(i.tally) AS tally,
    SUM(i.tick) AS tick
FROM link l
JOIN info i ON l.id = i.link_id
WHERE l.created BETWEEN '2013-01-01' AND '2014-01-01'
GROUP BY l.type ;

另一方面,我认为您不应该使用BETWEEN日期。这个条件将包括一整年加一天我怀疑是否有用。您可以改为使用:

WHERE l.created >= '2013-01-01' 
  AND l.created < '2014-01-01'    -- notice the missing equal sign here

,如果created列的类型为DATEDATETIMETIMESTAMP,则会产生一年的间隔。

答案 1 :(得分:0)

我想这就是你需要的东西

SELECT 
    SUM(CASE WHEN MOD(I.INFO_TYPE,2) = 0 THEN 1 ELSE 0 END) as type_B,
    SUM(CASE WHEN MOD(I.INFO_TYPE,2) <> 0 AND MOD(I.INFO_TYPE, 1) = 0
    THEN 1 ELSE 0 END) as type_A,
SUM(I.TALLY) AS TALLY, SUM(I.TICK) AS TICK
FROM link l
JOIN info i ON (l.id = i.link_id)
WHERE l.created BETWEEN '2013-01-01' AND '2014-01-01'
GROUP BY L.TYPE