0

I have a table with amounts only on some days, e.g.:

[DATE] [AMT]
11/1/2017 $123
11/1/2017 $50
11/3/2017 $123

How can I query the data and get:

11/1/2017 $173
11/2/2017 $0
11/3/2017 $123

I tried like:

SELECT Day([Date]) AS [Day], Nz(Sum(AMT),0) AS [Day Total]
FROM mytable
WHERE Month([Date])=11
GROUP BY Day([Date]);

But still it doesn't return 0s for days without data, any ideas?

Erik A
  • 31,639
  • 12
  • 42
  • 67
PizzaChip
  • 15
  • 3

4 Answers4

1

You need a table with all the days, so you can fill the holes, lets call it allDays

Get a list of dates between two dates using a function

Then your query is:

 SELECT a.[date], COALESCE(SUM([AMT]),0)
 FROM allDates a
 LEFT JOIN yourTable t
   ON a.[date] = t.[date]
 GROUP BY a.[date]
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
1

In Access, you can create a series of dates between the first and the last date, and then create an outer join to your summed data.

Here is how to create the date series:

Create a date table between two dates

Gustav
  • 53,498
  • 7
  • 29
  • 55
0

There are two simple solutions.

jjjjjjjjjjj
  • 417
  • 8
  • 28
  • I forgot to mention that is MS Access 2016 SQL so not all TSQL functions are available, e.g. the RedFilter complains about reserved words and the COALESCE above doesn't exist in Access, that's why I used Nz() – PizzaChip Nov 16 '17 at 21:41
  • @PizzaChip In that case I would go with a date series table. What date range are you using in your data? – jjjjjjjjjjj Nov 16 '17 at 21:44
0

I suggest you try the following query:

SELECT DATE_FORMAT(date, "%b") AS month, SUM(total_price) as total
FROM table
WHERE date <= NOW()
and date >= Date_add(Now(),interval - 12 month)
GROUP BY DATE_FORMAT(date, "%m-%Y"))
mmgross
  • 3,064
  • 1
  • 23
  • 32
Gaurav
  • 25
  • 3