MySQL Count多列语法

时间:2014-07-06 16:31:20

标签: mysql count

我有这张桌子:

CREATE TABLE IF NOT EXISTS `voertuiglijnen` 
(
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `voertuig` int(11) NOT NULL,
  `lijn` text NOT NULL,
  `publijn` int(11) NOT NULL,
  `rit` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);

这是一些示例输入:

|id    |voertuig    |lijn    |publijn    |rit
|------|------------|--------|-----------|-----
|1     |5376        |A060    |60         |1
|2     |5376        |A062    |62         |2
|3     |5376        |A062    |62         |3

我希望SQL结果用相同的“voertuig”显示每个“lijn”,然后通过“lijn”的出现来命令它。

SELECT DISTINCT `lijn`, `publijn`, count(*) as aantal 
FROM `voertuiglijnen` 
WHERE `voertuig` = '5376' 
ORDER BY aantal DESC

在这种情况下,应将A062作为第一个,将A060作为第二个。但它正在反过来做这件事。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

使用GROUP BY而不是DISTINCT:

SELECT `lijn`, `publijn`, count(*) as aantal
 FROM `voertuiglijnen`
 WHERE `voertuig` = '5376'
 GROUP BY 1,2
 ORDER BY aantal DESC