我有这张桌子:

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放在第二位。但这是相反的。

我在这里做错了什么?

最佳答案

使用GROUP BY代替DISTINCT:

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

关于mysql - MySQL Count多列语法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24597962/

10-12 06:18