I have a table with prices, date as a timestamp, the month of entry and the year of entry.
+++++++++++++++++++++++++++++
Price | Date | Month | Year |
+++++++++++++++++++++++++++++
9.00 |343345| 2 | 2013 |
3.00 |343445| 2 | 2013 |
4.00 |343245| 1 | 2013 |
1.00 |342245| 1 | 2013 |
5.00 |333355| 12 | 2012 |
So far I have this to list the monthly price totals, the problem is GROUP BY re-sorts the results so that it goes month 1, month 12 then month 2 where as I need the results to descend from the current month, month-by-month.
"SELECT month,SUM(price), FROM table GROUP BY month ORDER BY date DESC "
I'm using PHP if that helps.
It's treating your month as text instead of numeric. Cast it as an integer and it'll sort properly.
SELECT CAST(Month as int) as Month, SUM(PRICE), FROM table Group by month ORDER BY CAST(MONTH as int) desc
The problem is your date field is not stored as a datetime. Instead of ordering by it, order by your year and month fields instead (I presume you want to group by both of those fields).
SELECT year,month,SUM(price)
FROM table
GROUP BY year,month
ORDER BY year DESC, month DESC
If the year and/or month are stored as varchar, then cast them -- I suspect those are stored as integers though:
Cast your month to INT data type:
SELECT month,SUM(price), SUM(price), FROM table GROUP BY month ORDER BY cast(month as UNSIGNED) DESC
More: CAST
I had similar problem. I solved it by adding another column with 'date' type and convert all the different fields in dates. Then you can make selects within time range.
Related
This SQL is called by a Smarty File designed to download an .xlsx of the output. It works well for all months EXCEPT the Dec. (end of year) report. Something is needed to get it to cross the year-end boundary but I can't figure what. ? Thanks.
SELECT user_id, cert_name, from_email, created_at, phone as role,
delivery, user_street, user_city, user_state, user_zip,
user_country_id, standard_fee, expedited_fee
FROM support_tickets
WHERE nature = 2
AND user_id IS NOT NULL
AND created_at BETWEEN '2012-12-05 04:00:01' and date(concat_ws('-', #year, #month + 1, 1))
ORDER BY created_at DESC
Use date arithmetic, not string concatenation.
If you try to add #month+1 when month is 12, you get month 13, not month 1 of the next year. There is no month 13 in calendars currently in use.
For your case I would recommend using the LAST_DAY() function that is built into MySQL. This returns the last date in the current month of its argument.
Example:
mysql> SELECT LAST_DAY('2020-12-05') AS last;
+------------+
| last |
+------------+
| 2020-12-31 |
+------------+
I suspect you want the last day of the same month.
If you really want the first day of the next month, use date arithmetic:
mysql> SELECT LAST_DAY('2020-12-05') + INTERVAL 1 DAY AS next;
+------------+
| next |
+------------+
| 2021-01-01 |
+------------+
Is there a way to order my SQL results after they have been delivered? So far I have two values. My code currently returns the results and can sort by the dates ORDER BY date ASC
The database entries of interest are.
| date | weeks |
| 2020-07-01 | 2 |
| 2020-07-01 | 3 |
| 2020-07-01 | 5 |
Weeks represents how many weeks away the next date is. so 2020-07-21, 2020-08-03, and so on (I am able to return these values). The order by needs to be able to order the dates and take into account the week value from the closest week to the furthest.
I have tried just updating the database with a new field called final_date, although this makes everything cluttery.
When the data is returned, I can find the new date using:
$addWeeks = strtotime('+'.$numberOfWeeks.' weeks', strtotime($last));
Although, I cannot find a way to order the results by that new value.
The order by needs to be able to order the dates and take into account the week value from the closest week to the furthest.
I think you want:
select t.*
from mytable t
order by t.date + interval t.weeks week
Note that this assumes that column date is of date datatype, not string; else, you need to convert it to a date first, using str_to_date() for example.
mySQL dateTime range Query Issue
how get count of proceser in 2017 by same date like 2017-08-07
date | name
-----------------------
2017-08-31 | amr
-----------------------
2017-08-05 | ahmed
----------------- -----
2018-08-08 | moh
how get 2017-01-01 BETWEEN 2017-12-31
------------------------
count | date
-----------------------
2 | 2017
-----------------------
1 | 2018
SELECT count(*)
FROM item WHERE
date IN
( SELECT date
FROM item WHERE
(BETWEEN '2017-03-15' AND '2017-09-31'))
I couldn't find a duplicate for you, but I am sure there is one somewhere.
If you use GROUP BY and the DATE_FORMAT() function, you can COUNT() the occurrences in each group.
SELECT COUNT(*),DATE_FORMAT(`date`,'%Y') FROM `item` GROUP BY DATE_FORMAT(`date`,'%Y');
You can include a WHERE clause before GROUP BY if you need to omit certain ranges of time.
1, date is a reserved MySQL word. It would be best to name your column something else, but you can use it if you also specify the table name like table.date
2, there is no need for a sub-query. MySQL can do this in one query
SELECT count(`table.name`) as NUMBER, YEAR(`table.date`) as YR FROM item WHERE DATE(`table.date`) BETWEEN '2017-01-01' AND '2017-12-31'
BETWEEN is kind of a "ternary" operator, of the form x BETWEEN y AND z
You want:
`date` BETWEEN '2017-03-15' AND '2017-09-31'
for e.g
SELECT *
FROM api_call_log
WHERE account_sid='XXXXXXXXXXXX' AND
created_time >= 01-02-2016 00:00:00 AND
created_time <= 31-02-2016 23:59:59
ALLOW FILTERING
I am getting records from first month as well though I searched for second month.
It's difficult to say without seeing your table structure or relevant portions of your result set. But I did notice that you are not specifying a GMT offset, which means you are effectively querying by your default local offset. The problem, is that Cassandra stores by GMT+0000.
For example, if you have a negative GMT offset of say -0600 (like me), a query for GMT-0600 would miss 6-hours-worth of data from February 1st. For instance, if I have a row out there for 2016-02-01 01:00:00+0000, this query will not return it:
aploetz#cqlsh:stackoverflow> SELECT * FROm events WHERe monthbucket='201602'
AND eventdate >= '2016-02-01 00:00:00';
monthbucket | eventdate | beginend | eventid | eventname
-------------+-----------+----------+---------+-----------
(0 rows)
And that's because 2016-02-01 01:00:00+0000 is essentially 2016-01-31 19:00:00-0600. So if I add the GMT offset of 0000, I see the row.
aploetz#cqlsh:stackoverflow> SELECT * FROm events WHERe monthbucket='201602'
AND eventdate >= '2016-02-01 00:00:00+0000';
monthbucket | eventdate | beginend | eventid | eventname
-------------+--------------------------+----------+--------------------------------------+-------------------
201602 | 2016-02-01 01:00:00+0000 | b | 78d2c2b7-c4ec-408f-be37-eccc0c05727d | test month border
(1 rows)
My guess, is that you probably have the opposite problem (extra rows vs. missing rows) due to having a positive GMT offset. Not specifying your offset in your query could be why it is including rows from the previous month. And if that's the case, then you may want those rows.
Also, don't use ALLOW FILTERING. Like ever.
Try this
SELECT * FROM api_call_log WHERE account_sid='XXXXXXXXXXXX' AND jobs.created_at between '01-02-2016 00:00:00' and '31-02-2016 23:59:59';
And also check the DATE/TIME format of the date column
I have a table with a kind of weird date format in a column as varchar - this is the format that the company has provided me with - the T in the middle seems to mess things up.
EVENTID | EVENT_DATE | EVENT_DURATION
1 | 2012-10-14T06:00 | 15
2 | 2012-10-14T06:15 | 11
3 | 2012-10-14T06:26 | 14
4 | 2012-10-14T06:40 | 10
ect...ect
I have php code to return the current time in the exact same format (with the weird 'T' in the middle'
$thisin = DateTime::createFromFormat('Y-m-d\TH:i', date('Y-m-d\TH:i'));
$thisin->setTimeZone(new DateTimeZone('UTC'));
$thisout= $thisin->format('Y-m-d\TH:i');
Assuming that today is the 14th and the current time is 06:21, how do i query the current row based on duration that matches "$thisout from php" and the next five rows (in the future).
Because the current time and date are returned from php as "2012-10-14T06:21" The query should output
2 | 2012-10-14T06:15 | 11 (Now SHowing)
3 | 2012-10-14T06:26 | 14
4 | 2012-10-14T06:40 | 10
ect ect
I have been scratching my head for hours, DATE_FORMAT() Doesn't seem to work, and I think it may be the T in the middle. I am aslo have to figure out how to use duration to determine if the current time applies to a specific row.
This does not work
SELECT DISTINCT EVENTID, EVENT DATE, EVENT_DURATION
FROM epg_event
WHERE DATE_FORMAT(EVENT_DATE, '%Y-%m-%dT%H:%i') >= DATE_FORMAT(NOW(), '%Y-%m-%dT%H:%i')
ORDER BY EVENT_DATE ASC LIMIT 5
Any Ideas?
You should load the date information into a Date column rather than a varchar column in the database. As previously noted this is the ISO format for dates.
Need to add in the interval.
where event_date + INTERVAL duration MINUTE >= NOW()
I'm not currently able to test it, but something like this might work:
SELECT DISTINCT EVENTID, EVENT_DATE, EVENT_DURATION
FROM epg_event
WHERE (event_date <= NOW()) AND (ADDTIME(event_date, INTERVAL event_duration MINUTE) >= NOW())
ORDER BY event_date ASC LIMIT 5
DATE_FORMAT() is meant for formatting a DATETIME field, not the other way around. And, as mentioned earlier, you event_date should be a DATETIME field and you should convert the time when you import the data to your database.