0

I have the following MySQL Query:

SELECT date, time, custom_id, Number
FROM traffic t
WHERE CONCAT(date, " ", time) BETWEEN "01/06/2014 00:00" AND "01/10/2014 23:00"
AND Number = 
(SELECT MAX(CAST(Number as SIGNED)) FROM traffic WHERE t.date = date and t.custom_id = custom_id)
ORDER BY date, CAST(Number as SIGNED) DESC, custom_id

This is the SQLFiddle in MySQL (working): http://sqlfiddle.com/#!2/6e1248/3

How can I convert/translate it to MS SQL? SQLFiddle (not working): http://sqlfiddle.com/#!6/6e124/1

Thanks in advance

3
  • why are date and time separate columns? And unless date is in a proper DATE format, this won't work in MySQL either! Commented Feb 11, 2014 at 14:29
  • The query presumably doesn't work in MySQL because of the date time formats. The between will not work when it crosses month boundaries. Commented Feb 11, 2014 at 14:30
  • sqlfiddle.com/#!6/6e124/21 Commented Feb 11, 2014 at 14:32

2 Answers 2

2
SELECT date, time, custom_id, Number
FROM traffic t
WHERE CONCAT(date, ' ', time) BETWEEN '01/06/2014 00:00' AND '01/10/2014 23:00'
AND Number = 
(SELECT MAX(CAST(Number as smallint)) FROM traffic WHERE t.date = date and t.custom_id = custom_id)
ORDER BY date, CAST(Number as smallint) DESC, custom_id
Sign up to request clarification or add additional context in comments.

2 Comments

Worked perfectly. Exact same result, Thanks!
Thanks to you, with the link to SQLFiddle is all more simple!
1

The main issue is that SQL server doesn't like " to enclose strings, these will get treated as a column name removing these (and the CASTs) works:

SELECT date, time, custom_id, Number
FROM traffic t
WHERE CONCAT(date, ' ', time) BETWEEN '01/06/2014 00:00' AND '01/10/2014 23:00'
AND Number = 
(SELECT MAX(Number) FROM traffic WHERE t.date = date and t.custom_id = custom_id)
ORDER BY date, Number DESC, custom_id

Edit: Whoops, just noticed cast is needed. See the answer by @bdn02 for an example.

1 Comment

That's why I wasn't getting the result I was expecting. 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.