Hector
Hector

Reputation: 682

SQL View to show interval of 12 months and by year

Right now one of the other programmers wrote this view to show interval of 6months. How do i write this so that it shows interval of 12 months grouped by month but only for year 2011

I'd like to copy it for a separate view of 12 months grouped by month but only for year 2012

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` 
SQL SECURITY DEFINER VIEW `vw_dash_bymonth`AS
select 
  month(from_unixtime(`tbl_services`.`datetime`)) AS` month1`,
  date_format(from_unixtime(`tbl_services`.`datetime`),'%Y') AS` year1`,
  date_format(from_unixtime(`tbl_services`.`datetime`),'%d') AS `day1`,
 `tbl_services`.`datetime` AS `realdate`,sum(`tbl_services`.`gallons`) AS `gallons`,
 count(0) AS `service`,
 round(avg(`tbl_services`.`gallons`),1) AS `average`
from `tbl_services`
where (from_unixtime(`tbl_services`.`datetime`) > (now() - interval 6 month))
group by month(from_unixtime(`tbl_services`.`datetime`))

Upvotes: 1

Views: 2199

Answers (3)

onlinefilmi
onlinefilmi

Reputation: 11

SELECT DISTINCT FROM_UNIXTIME('date','%m-%Y') AS month,
COUNT(`id`) AS count
FROM 'blog'
GROUP BY month
ORDER BY month DESC LIMIT 0,12

Upvotes: 1

Mike
Mike

Reputation: 8545

If you look at the where clause

where (from_unixtime(`tbl_services`.`datetime`) > (now() - interval 6 month))

I believe this is getting the dates from everything from 6 months ago until today. If you want 12 months in 2011 I think you could replace that line with something like:

where (from_unixtime(`tbl_services`.`datetime`) >= DATE('2011-01-01 00:00:00')) 
  AND (from_unixtime(`tbl_services`.`datetime`) < DATE('2012-01-01 00:00:00'))

Although I don't know MySQL (just SQLServer) so if this doesn't work, hopefully someone else can tell me where I went wrong.


It can be simplified to:

where (from_unixtime(`tbl_services`.`datetime`) >= '2011-01-01') 
  AND (from_unixtime(`tbl_services`.`datetime`) < '2012-01-01')

Upvotes: 2

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115630

SELECT
    MONTH( UNIX_TIMESTAMP( t.`datetime`) ) AS month1,
    DATE_FORMAT( UNIX_TIMESTAMP( t.`datetime`), '%Y' ) AS year1,
    DATE_FORMAT( UNIX_TIMESTAMP( t.`datetime`), '%d') AS day1,
    t.`datetime` AS realdate,
    SUM(t.gallons) AS gallons,
    COUNT(*) AS `service`,
    ROUND( AVG( t.gallons ), 1 ) AS `average`
FROM 
      tbl_services AS t
  CROSS JOIN
      ( SELECT 2011 AS YearToCheck
      ) AS c
WHERE t.`datetime` >= UNIX_TIMESTAMP( MAKEDATE( YearToCheck, 1 ) )
  AND t.`datetime` < UNIX_TIMESTAMP( MAKEDATE( YearToCheck+1, 1 ) )
GROUP BY MONTH( FROM_UNIXTIME( t.`datetime` ) )

Upvotes: 0

Related Questions