Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select & group by a period of time (timestamp)


I want to select the count number and group by a period of time (month, week, day, hour , ...) . So for example I want to select the number of rows and group them by 24h.
My table is created as follow. The date is timestamp.

CREATE TABLE MSG
(
   MSG_ID decimal(22) PRIMARY KEY NOT NULL,
   MSG_DATE timestamp,
   FILE_REF varchar2(32),
   FILE_NAME varchar2(64),
   MSG_TYPE varchar2(2),
);
CREATE UNIQUE INDEX PK_FEI_MSG ON MSG(MSG_ID);


I tried with this query. With length depending on the time period. But how can I group from now .

SELECT substr(MSG_DATE, 1,length),COUNT(*) as total FROM MSG GROUP BY substr(MSG_DATE, 1, length)


But how can I group the date from now + time_period ?

like image 549
Raymond Chenon Avatar asked Mar 14 '11 10:03

Raymond Chenon


People also ask

What does SQL Select do?

The SQL SELECT Statement The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.

What is select in SQL with example?

The SELECT TOP statement is used to limit the number of rows which returns the result of the query. For example, if want to retrieve only two rows from the table we can use the following query. Therefore, we can limit the result set of the query. In the following SQL examples, we will limit the result set of the query.

What is select command?

Select command is used to fetch the data in a set of records from a table, view or a group of tables, views by making use of SQL joins.

How can I see last 10 rows in SQL?

SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query. mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records.


1 Answers

You can group by the TO_CHAR function.

select to_char(msg_date, 'X')
      ,count(*)
  from msg
 group 
    by to_char(msg_date, 'X')

...where X is the format specification:

  • YYYY = 4-digit Year
  • MM = Month of year
  • DD = Day in month
  • WW = Week
  • HH24 = Hour of day

You can combine them pretty much however you like

like image 83
Ronnis Avatar answered Oct 04 '22 02:10

Ronnis