0

I want to select value from given date and same time if no row in that date then it should return 0 in that specific date. here is my query

SELECT
    sum(`value`) AS `VALUE`,
    serverTimeStamp AS date
FROM
    table1 t1

WHERE
    serverTimeStamp BETWEEN CONVERT_TZ(
        '2016-03-21 00:00:01',
        '+00:00',
        '-05:30'
    )
AND CONVERT_TZ(
    '2016-03-25 23:30:36',
    '+00:00',
    '-05:30'
)
GROUP BY
    YEAR (date),
    MONTH (date),
    WEEK (date),
    DAY (date)
ORDER BY
    date ASC;

Output :

value date

96 2016-03-21 00:00:01

76 2016-03-23 00:00:01

56 2016-03-25 00:00:01

Expected Output :

value date

96 2016-03-21 00:00:01

0 2016-03-22 00:00:01

76 2016-03-23 00:00:01

0 2016-03-24 00:00:01

56 2016-03-25 00:00:01

Any idea to achieve this?

table1 :

**id value serverTimeStamp**

 1   96 2016-03-21 00:00:01

  2  76 2016-03-23 00:00:01

 3  56 2016-03-25 00:00:01  

but what i am expecting in query if there is no row in given date then it should be 0 and specific date like below

value date

96 2016-03-21 00:00:01

0 2016-03-22 00:00:01

76 2016-03-23 00:00:01

0 2016-03-24 00:00:01

56 2016-03-25 00:00:01
MMMMS
  • 2,179
  • 9
  • 43
  • 83

2 Answers2

1

You need to create a table storing your possible dates and then LEFT JOIN your query to it, so that every date that is missing from your query would still be included in the output, but with the value 0.

How to generate data into table with dates: Generate series equivalent in MySQL

You just need to alter this query to include an INSERT INTO your table with dates.

Then, depending on how you insert your date (with time - if it's static coming from your query, or without time - if it's changing) you need to join that table with your existing query on the column value if it contains time, or if it doesn't, on the date part extracted from serverTimeStamp from your query

Community
  • 1
  • 1
Kamil Gosciminski
  • 16,547
  • 8
  • 49
  • 72
0

Create a stored procedures and do like below to get your desired output

create table temp_data
(
id int,
value int,
server_date datetime 
);

Drop temporary table if exists temp_generate_dates; 
create temporary table temp_generate_dates 
( 
temp_date datetime 
); 

insert into temp_generate_dates 
select adddate('2016-03-21 00:00:01', @num:=@num+1) as date 
from 
temp_data, 
(select @num:=-1) num 
limit 5; 


select coalesce(t1.value,0),t2.temp_date from temp_generate_dates t2 
left join temp_data t1 on t2.temp_date = t1.server_date ;
Ankit Agrawal
  • 2,426
  • 1
  • 13
  • 27