0

I have this table:

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`)
);

This is some sample input:

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

I want the SQL result to display each "lijn" with the same "voertuig", and then order it by occurence of "lijn".

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

In this case, it should put A062 as first, and A060 as second. But it's doing it the other way around.

What am I doing wrong here?

1 Answer 1

1

Use GROUP BY instead of DISTINCT:

SELECT `lijn`, `publijn`, count(*) as aantal
 FROM `voertuiglijnen`
 WHERE `voertuig` = '5376'
 GROUP BY 1,2
 ORDER BY aantal DESC
Sign up to request clarification or add additional context in comments.

1 Comment

Ah yes of course! I totally forgot about GROUP BY. It's been a while! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.