如何计算不同的行

时间:2012-12-16 17:39:35

标签: mysql

SELECT
    HOUR (`Timestamp`) AS HOUR,
    COUNT(*) AS Alarms

FROM
    `alarms`
WHERE
    `Siteindex` IN ('4, 5, 8, 10, 11, 15')
AND `Datestamp` = '2012-11-07'
GROUP BY
    HOUR (`Timestamp`);

此代码仅在IN ('4, 5, 8, 10, 11, 15')的每个ID都有Datestamp = '2012-11-07'的情况下才有效,但是如何只计算那些拥有它的人?

例如,上面的代码返回NULL,因为在2012-11-07中只有15行有一些行,但我需要它不注意其他行并返回所有

3 个答案:

答案 0 :(得分:1)

您的where条款很可能是问题

WHERE `Siteindex` IN ('4, 5, 8, 10, 11, 15')

根据siteindex的类型,您应将其更改为

WHERE `Siteindex` IN (4, 5, 8, 10, 11, 15)

WHERE `Siteindex` IN ('4', '5', '8', '10', '11', '15')

答案 1 :(得分:0)

我并不完全清楚你在问什么,但如果你只想找到符合搜索条件的行数,我会尝试一些谎言:

SELECT COUNT(*)
FROM alarms
WHERE Siteindex IN ('4,5,8,10,11,15') AND Datestamp = '2012-11-07';

答案 2 :(得分:0)

试试这个

      SELECT  HOUR (`Timestamp`) AS HOUR,

  COUNT(Siteindex) AS Al

 FROM ( SELECT Siteindex FROM alarms WHERE `Siteindex` IN (4, 5, 8, 10, 11, 15))
`alarms`
 WHERE
  `Datestamp` = '2012-11-07'
GROUP BY
HOUR ;

这只会计算你拥有的那些。