16

I am trying to figure out the proper syntax for getting query result I need. Here is the scenario:

I am designing a SaaS application and have a table called trips, like so:

table.trips  
- trip_id (pk, ai)  
- client_id (fk)  
- shop_id (fk)
- trip_date (date)

I need to be able to get the number of trips in the table for each day (by shop_id) and then deliver the number of TRIPS per trip_date, like:

DATE         | TRIP SUM  
--------------------------
01-01-2011   | 3
01-02-2011   | 2  
01-03-2011   | 5

Any thoughts on the proper syntax?

1
  • What do you mean by "by shop id"? There is no shop_id in your resultset. Commented Mar 23, 2011 at 15:11

5 Answers 5

32
SELECT COUNT(*), trip_date , shop_id 
FROM trips 
GROUP BY trip_date , shop_id
Sign up to request clarification or add additional context in comments.

3 Comments

You either need to remove the WHERE or put in a WHERE condition. The way it is is invalid SQL.
Perfect:-) Thanks for your help. Added WHERE shop_id=# and it worked perfectly. Cheers.
SELECT COUNT(*) AS customvar always helps with the returned results
12

If the date column also stores hour and minute you will need to apply a substring function to the date, to only have the yyyy-mm-dd part of the date column, like this:

SELECT COUNT(*), substring(trip_date,1,10)
FROM trips
GROUP BY substring(trip_date,1,10);

1 Comment

This just saved me ages trying to compile a count of rows by date but not time
4

Something like this?

select 
   DATE(trip_date) as [DATE],
   count(1) as [TRIP SUM]
from
   trips
group by
   DATE(trip_date), shop_id

I'm not a mySQL guy, but you will need to use a T-SQL DatePart equivalent, where I have used the DATE() function in order to strip the time portion of the date.

Comments

2
select trip_date,count(*)
from trips
where shop_id=[the shop id]
group by trip_date

This will work as long as the date is on the format you showed. If it has also time then you have to remove the time.

Also I do not know if the client_id has to come in in this query, if you have to group by it also then you have to put it along side trip_date on select or group. If you want to filter by it put it in the where.

Comments

2
SELECT shop_id, trip_date, count(trip_id)
FROM trips
GROUP BY shop_id, trip_date

1 Comment

Please take a moment to expand on this code-only answer regarding how it works and why it is a good idea. When new users see code-only answers posted by high-repped users they think that this is "how it is done on SO". Please role model better posting behavior for their sake -- not to mention for the benefit of future researchers.

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.