I want to report statistics on the number and value of financial transactions I am recording in a transactions table. I store a "createdDateTime" dateTime field for each transaction. I thought a useful statistic would be the average number of transactions by day of week. I can get the total number of transactions for each day of the week with:
--transactions per day select 'Day' = Case datePart(dw,t.createdDateTime) when 1 then 'Sun' when 2 then 'Mon' when 3 then 'Tue' when 4 then 'Wed' when 5 then 'Thu' when 6 then 'Fri' when 7 then 'Sat' end, count(t.id) from transaction t group by datePart(dw,t.createdDateTime) order by datePart(dw,t.createdDateTime)
I believe it boils down to getting the total number of transactions for each day of the week as above and then figuring out how many of each day exists in the date range defined by the min(createdDateTime) and max(createdDateTime), e.g. number of Sunday transactions / number of Sundays... I cannot figure out how to count the many times each day occurs. Also, I suppose I'll have the same problem with weeks and months when I get that far.
Congratulations for thinking ahead to finding useful applications for your data. Obtaining aggregates by day of week is certainly among the common statistics one might seek from transaction data.
Congratulations also for the developing query as far as you did. Grouping by a day number (1, 2, ...) while displaying a day name abbreviation (Sun, Mon, ...) is somewhat beyond beginner SQL.
I have some very good news. You need not concern yourself with counting the number of days in each group. Yes, there may be a different number of Sundays than Mondays in the selected date range. Yes, the number of transactions for each day must be divided, as you anticipated, by how many of each day exist in the date range. The good news is that grouping counts them for you. Just use the AVG function. If there are 56 transactions for 2 Sundays in the date range, and 63 transactions for 3 Mondays, the AVG will be 28 for Sunday and 21 for Monday.
For More Information
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.