Oracle/SQL - Grouping items by action by day over time
Asked Answered
A

2

18

Hi all I have a 'widget' table that has the following columns: widget, action, timestamp_. What we want to do is pull all the widgets that were rejected more than once a day between certain dates. So here's an example table

widget      action      timestamp_
-------------------------------------------
type1       reject      2011-05-10 08:00:00
type1       reject      2011-05-10 09:00:00
type1       reject      2011-05-10 09:30:00
type2       reject      2011-05-11 09:30:00
type3       reject      2011-05-11 09:30:00
type1       reject      2011-05-11 09:30:00
type1       reject      2011-05-11 09:30:00
type2       reject      2011-05-12 10:30:00
type2       reject      2011-05-12 12:30:00
type3       reject      2011-05-12 12:30:00

So I anticipate wanting to see results in one of these two manners....

Between date x and y there were two widgets that were rejected multiple times in single days

This would see that type1 was rejected more than once in a day as was type2 thus the count is: 2

OR

Display each widget along with the date that it was rejected more than once and how many times. Example..

widget      date            count
---------------------------------
type1       2011-05-10      3
type1       2011-05-11      2
type2       2011-05-12      2

This would probably be the preferred output... but how?

Thanks in advance!

Athome answered 20/5, 2011 at 3:14 Comment(0)
J
25

This would give your output:

SELECT Widget, to_char(timestamp_,'YYYY-MM-DD'), Count(Widget)
FROM Widget
WHERE timestamp_ BETWEEN to_date('YYYY-MM-DD HH24:MI:SS','%date1%') AND to_date('YYYY-MM-DD HH24:MI:SS','%date2%')
AND action LIKE 'reject'
GROUP BY Widget, to_char(timestamp_,'YYYY-MM-DD')
HAVING Count(Widget) > 1;

Of course, you'll want to replace the date variables.

Jam answered 20/5, 2011 at 3:44 Comment(5)
Replaced out the date variables and receive this error: "CNT": invalid identifierAthome
@dscl: Sorry, I couldn't try it against an Oracle db. Please try it now.Jam
No worries; however now I get the same error but for Date_. "DATE_": invalid identifierAthome
@dscl: Turns out Oracle can only handle column alias names in its ORDER BY clause. Bummer. I updated the query for you.Jam
Needed to swap the format and the date string in to_date to get this to work.Aleasealeatory
N
1

Try the below one and you will get what you want :-

  Select widget,convert(varchar,[timestp],102) As Date,COUNT(timestp) as Count
  From MTest
  group by widget,[action],convert(varchar,[timestp],102)
  having COUNT(timestp)>1
Northwards answered 20/5, 2011 at 3:44 Comment(2)
I added in a where clause on the action = 'rejected' so I don't get back unneeded results. I also get an error though: 'missing expression'Athome
you are trying in sql Server or Oracle??Northwards

© 2022 - 2024 — McMap. All rights reserved.