Unixtime & mysql - php

I have a field on my table which is called X, and I store unixtime(php -> time()).
My question is:
How can I list all the months from my DB, something like: 6.2009 8.2009 etc..
And my second question is:
How can I make a query to list all the informations based on a month and year on the same field X(i store unixtime), I know this doesn't work, but mabe you can understand it better: where date = '06.2009'
Any solutions?

List all months:
SELECT DISTINCT EXTRACT(YEAR_MONTH FROM FROM_UNIXTIME(X)) FROM MyTable;
Return all rows with a given year & month:
SELECT * FROM MyTable
WHERE EXTRACT(YEAR_MONTH FROM FROM_UNIXTIME(X)) = 200906;

Try this
SELECT FROM_UNIXTIME(X,'%m.%Y') FROM TABLE GROUP BY FROM_UNIXTIME(X,'%m.%Y')
SELECT * FROM TABLE WHERE FROM_UNIXTIME(X,'%m.%Y')='06.2009'
Bye

To answer your first question, you would do this with grouping:
SELECT FROM_UNIXTIME(timestamp_column, '%c.%Y') AS month, some_other_column FROM table_name GROUP BY month;
As for your second question, this depends on what you're trying to do. For example:
SELECT AVG(payment), SUM(*), FROM_UNIXTIME(timestamp_column, '%c.%Y') AS month, some_other_column FROM table_name WHERE timestamp_column BETWEEN UNIX_TIMESTAMP(200906) AND UNIX_TIMESTAMP(200907) - 1 GROUP BY month;
Would return the average of the payments and the number (sum) of rows for each group.
To get information ungrouped from a specific timeframe, reduce the query like so:
SELECT payment, some_other_column FROM table_name WHERE timestamp_column BETWEEN UNIX_TIMESTAMP(200906) AND UNIX_TIMESTAMP(200907) - 1;

Related

Fetching sum of amount for a specific year from mysql

I have the following table with dummy values in mysql database:
id cnic amount depositDate receivedBy receivingZone remarks
1 11111 10000 01-Nov-2019 11111 1 Ok
2 11111 10000 07-Nov-2019 11111 1 ok
Now i want to get the sum of amount from the table for specific year (2019 in this case) where the year came from current timestamp (it may be 2020, 2021 etc depends on the current date)
Any help plz
You can use the YEAR function to get the year of the depositDate column and also the current year and then sum only the values which match:
SELECT SUM(amount) AS amount
FROM yourtable
WHERE YEAR(STR_TO_DATE(depositDate, '%d-%b-%Y')) = YEAR(CURDATE())
You can try below -
select sum(amount)
from tablename
where year(depositdate)=year(now())
I would write the WHERE clause to be sargable:
SELECT SUM(amount)
FROM yourTable
WHERE depositDate >= DATE_FORMAT(NOW() ,'%Y-01-01') AND
depositDate < DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 1 YEAR) ,'%Y-01-01');
This approach, while a bit more verbose than the other answers which use the YEAR() function, would allow an index on the depositDate column to be used.
Based on your sample year, we need to recognize first the date using str_to_date
select sum(amount)
from tableA
where year(now()) = year(str_to_date(depositdate, '%d-%b-%Y'))

How to find new client?

I ran into one problem that I can not solve for 3 days already.
The problem is current, there is a database of two columns of date ("yyyy-mm") and the phone number is unique non-repeating. I want to find out how many new customers each month. Well, the formula is roughly current (the new client is the first month + the new client is the next month ....). If the customer meets the first month he is considered a new customer, then it is on the other month, he is missing a new customer.
try Something like this:
select year(f2.DateColumn) YearCol, month(f2.DateColumn) MonthCol, count(f2.PhoneNumber) NbNewPhone
from (
Select f1.*, row_number() over(partition by f1.PhoneNumber order by f1.DateColumn) rang
from yourTable f1
) f2
where f2.rang=1
group by year(f2.DateColumn), month(f2.DateColumn)
order by 1, 2
or if you column is not a date :
select f2.DateColumn, count(f2.PhoneNumber) NbNewPhone
from (
Select f1.*, row_number() over(partition by f1.PhoneNumber order by f1.DateColumn) rang
from yourTable f1
) f2
where f2.rang=1
group by f2.DateColumn
order by 1, 2
As per your example just below count is sufficient:
Select DateColumn, Count(PhoneNumber) from yourTable
Group by DateColumn
If Datecolumn is real date as yyyy-mm-dd with date datatype you can query as below:
Select year(datecolumn), month(datecolumn), count(PhoneNumber) from yourTable
group by year(datecolumn), month(datecolumn)

PHP and SQL - How to select highest sum of all months in a current year?

So I have table 'item' in database with attributes: id, dateItem, price.
I want to find MAX(SUM(price)) for some month in a current year.
id dateItem (Format: yyyy-mm-dd) price
1 25.06.2015. 986,69
2 21.06.2015. 1564
3 22.03.2015. 23,56
4 21.03.2015. 187,23
5 01.03.2015. 489,33
6 06.10.2015. 975,26
I came up with something like this, but I know it's not ok. Please, help :s
$sql = "SELECT MAX(SUM(price)) FROM item WHERE DATE('Y') = 2015 AND
dateItem between DATE('Y/m/1') and DATE('Y/m/31')";
You can't nest aggregation functions. You need to use a subquery.
SELECT MAX(pricesum)
FROM (SELECT SUM(price) AS pricesum
FROM item
WHERE YEAR(dateItem) = YEAR(NOW())
GROUP BY MONTH(dateItem)) AS subquery
You can do this with ORDER BY and LIMIT:
SELECT SUM(price) AS pricesum
FROM item
WHERE YEAR(dateItem) = YEAR(NOW())
GROUP BY MONTH(dateItem)
ORDER BY pricesum DESC
LIMIT 1;
If you want to know the month as well, you can include that in the SELECT clause.

SQL LIMIT by end of the month

I have some code with me:
$sql = "SELECT * FROM palash ORDER BY id DESC LIMIT 31";
I want the LIMIT 31 to be LIMIT END OF THE MONTH
Use the LAST_DAY() function.
Takes a date or datetime value and returns the corresponding value for
the last day of the month. Returns NULL if the argument is invalid.
mysql> SELECT LAST_DAY('2003-02-05');
-> '2003-02-28'
mysql> SELECT LAST_DAY('2004-02-05');
-> '2004-02-29'
mysql> SELECT LAST_DAY('2004-01-01 01:01:01');
-> '2004-01-31'
mysql> SELECT LAST_DAY('2003-03-32');
-> NULL
In your case do this:
SELECT *
FROM palash
WHERE your_date_column <= LAST_DAY(CURDATE())
ORDER BY id DESC
Avoid solutions like OlivierH's (no offense, Olivier). Functions applied on your columns make it impossible for MySQL to use an index.
You can limit to current month with this conditions :
SELECT *
FROM palash
WHERE MONTH(my_date_column) = MONTH(CURDATE())
AND YEAR(my_date_column) = YEAR(CURDATE())
You can then adjust it to get previous dates too.
EDIT / Other way : to stay close to your original idea and to still have a full SQL solution, you can get number of days in current month with LAST_DAY :
DAY(LAST_DAY(my_date_column))
Here is one way you can do it
CREATE TABLE [dbo].[Dates](
[DateColumn] [datetime] NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Dates]
([DateColumn])
VALUES
('2015-01-04 13:00:00'),
('2015-01-06 13:00:00'),
('2015-02-05 14:00:00')
GO
----Last Day of Current Month
Declare #LastDayOfCurrentMonth datetime = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
SELECT *
FROM Dates
Where DateColumn < #LastDayOfCurrentMonth

Combining two MYSQL Queries into a single one

I am trying to combine two MYSQL Queries into one. What I want to do is select the first and last row added for each day and subtract the last column for that day from the first column of that day and output that. What this would do is give me a net gain of XP in this game for that day.
Below are my two queries, their only difference is ordering the date by DESC vs ASC. the column in the database that i want to subtract from each other is "xp"
$query = mysql_query("
SELECT * FROM (SELECT * FROM skills WHERE
userID='$checkID' AND
skill = '$skill' AND
date >= ".$date."
ORDER BY date DESC) as temp
GROUP BY from_unixtime(date, '%Y%m%d')
");
$query2 = mysql_query("
SELECT * FROM (SELECT * FROM skills WHERE
userID='$checkID' AND
skill = '$skill' AND
date >= ".$date."
ORDER BY date DESC) as temp
GROUP BY from_unixtime(date, '%Y%m%d')
");
SELECT FROM_UNIXTIME(date, '%Y%m%d') AS YYYYMMDD, MAX(xp)-MIN(xp) AS xp_gain
FROM skills
WHERE userID = '$checkID'
AND skill = '$skill'
AND date >= $date
GROUP BY YYYYMMDD
This assumes that XP always increases, so it doesn't need to use the times to find the beginning and ending values.
If that's not a correct assumption, what you want is something like this:
SELECT first.YYYYMMDD, last.xp - first.xp
FROM (subquery1) AS first
JOIN (subquery2) AS last
ON first.YYYYMMDD = last.YYYYMMDD
Replace subquery1 with a query that returns the first row of each day, and subquery2 with a query that returns the last row of each day. The queries you posted in your question don't do this, but there are many SO questions you can find that explain how to get the highest or lowest row per group.

Categories