tags:

views:

139

answers:

3

That's a really awkward title :)

I need to write a report that generates a list of declines by date. The date is store as a datetime field and is returning the number of declines by datetime.

Here's my SQL:

select ps.date_scheduled, count(*) from payments_schedule ps
left join invoices i on i.invoice_id=ps.invoice_id
left join orders o on o.order_id=i.order_id
where ps.date_scheduled>'2009-06-01 00:00:00'
group by ps.date_scheduled

2009-06-25 14:13:04 1 2009-06-25 14:13:07 1 ..etc...

Not cool. What I want is this: 2009-06-25 25 2009-06-26 31 etc...

How do I do that? Thanks :)

+4  A: 
GROUP BY DATE(ps.date_scheduled)
Alex Barrett
This is what I tend to use, although I've never benchmarked it. Not sure if MySQL uses an index (if available) for this or if it re-calculates each record's DATE() every time. If it re-calculates, a new column might be in order.
ceejayoz
A: 

Change your query to select DATEADD(day, 0, DATEDIFF(day, 0, ps.date_scheduled)). This will preserve only the date portion of the date-time. You will also need to group by the same expression.

EDIT: This is how to solve the problem for SQL Server.

Adamski
+7  A: 
SELECT  CAST(ps.date_scheduled AS DATE), COUNT(*)
FROM    payments_schedule ps
LEFT JOIN
        invoices i
ON      i.invoice_id = ps.invoice_id
LEFT JOIN
        orders o
ON      o.order_id = i.order_id
WHERE   ps.date_scheduled > '2009-06-01 00:00:00'
GROUP BY
        CAST(ps.date_scheduled AS DATE)
Quassnoi
Ahhh - cast. Thanks!
jeffkolez
Quass - is CAST more efficient than DATE()?
Paolo Bergantino
@Paolo: no, they're complete synonyms. I prefer this syntax to avoid confusion with DAY() which returns the day of month.
Quassnoi
Ah, thanks for clarifying. +1 as always :)
Paolo Bergantino