I don't even know how to ask this question...
So there is a database in place in which the columns are the months of the year:
January | February | March
Then each column has it's values:
jan1 | feb1 | mar1
jan2 | feb 2 | mar2
jan3 | feb3 | mar3
Sorry, I didn't know how to insert a table in Stack Overflow.
So when I run a query, I was wondering if there was a way mysql can automatically identify the current month, and use that to select the corresponding column.
So if the current month is January, then the SELECT would look like this:
$select = "SELECT UID, JANUARY FROM table WHERE UID = '1'";
That would bring back the column data for January where the UID = 1.
But when it's February, the query needs to automatically adjust the SELECT statement to select February.
I am not even sure if this is possible. I just wanted to see if anyone might know if there is a way to do this.
Use PHP built-in date() function, specified here.
date("F") // returns full string representation of current month like "January"
The code would then look something like this:
$select = "SELECT UID, ".date("F")." FROM table WHERE UID = '1'";
If you want a pure SQL solution, go for this:
select uid,
case month(curdate())
when 1 then january
when 2 then february
when 3 then march
when 4 then april
when 5 then may
when 6 then june
when 7 then july
when 8 then august
when 9 then september
when 10 then october
when 11 then november
when 12 then december
end as month_data
from mytable
where uid = '1';
Here is a fiddle.
MySQL has no function similar to eval(), so you have to include some long code like #trincot's answer. But if you don't mind using a prepared statement it can be done in a clearer way (IMHO):
set #s = CONCAT('SELECT ', MONTHNAME(NOW()), ' FROM meses');
PREPARE stmt FROM #s;
EXECUTE stmt;
Related
I'm trying to grab SQL data via PHP with a tally for case types each week to display like so:
Week 1 | Date From | Volume
Week 2 | Date From | Volume
Week 3 | Date From | Volume
and so on... without having to manually for each week. I have week number variables set as the business Year starts in July, so Week 1 is the first week in July. Ideally I'd like to use the company weeks but will settle for start of normal year. I've started with this:
SELECT YEARWEEK(date) as weekNum, MIN(sr_mob.`date`) as start_date,
count(*) as numRecords
FROM sr_mob
WHERE outcome='Escalated'
GROUP BY YEARWEEK(date)
This gives me the return data, but the start_date varies depending on when first entry was that week.
Is there any way to define a week in PHP then query the table (which doesn't contain the week numbers) to get what I'm after? Or does this sound like I'll manually have to request each week...
I can run a single query with say:
$Week1 ($week1=20180731-7;)
I guess what I am looking for is a way of doing a for each or while, using the $week variable, without having to write out 52 variables, if that makes sense.
Using reference from: https://stackoverflow.com/a/30373395/2397717
SELECT
YEARWEEK(date) as weekNum,
STR_TO_DATE(CONCAT(YEARWEEK(date),' Monday'), '%X%V %W') as start_date,
count(*) as numRecords
FROM sr_mob
WHERE outcome='Escalated'
GROUP BY YEARWEEK(date)
Hey guys i want to create one tree based data in my html view from mysql.
I have one table salary_slip there 2 columns pay_month and pay_year.
data is like this:
pay_month pay_year
February 2014
march 2014
January 2015
February 2015
April 2015
may 2015
June 2015
January 2016
march 2016
December 2016
So now i want to create tree view for the same.so, if user will click on 2016(pay_year) onclick this all data in pay_month in front of 2016 should be display in tree format and same for the all.
My current query is:
select
PAY_MONTH,
PAY_YEAR
from
india_salary_slip_details
where
EMPLOYEE_ID = 34
group by
pay_year
By this i got my data:
but i can only see each year's first month only.
please provide me with better query so i can get my result.
image for the same:current data from my query
A major part of your problem comes from the use of GROUP BY, which is used for, well, grouping.
MySQL has different handling of GROUP BY than other DBMS' that require all non-aggregate fields to be listed in the GROUP BY clause. MySQL give you enough rope with which to hang yourself (so to speak), which is why you didn't get an error for what is clearly not an intended use of GROUP BY.
Depending on how your front end is handling the data, you have a few options.
Option 1) Have it load (ordered) and use the output loop to determine the change in year.
SQL Query:
SELECT
PAY_MONTH,
PAY_YEAR
FROM
india_salary_slip_details
WHERE
EMPLOYEE_ID = 34
ORDER BY
pay_year,
pay_month -- we want it ordered by year, then month, though this will be alphabetical due to the data type
PHP Code:
<?php
$year = NULL;
foreach ($result as $row) { // Assuming your result is stored as $result
if ($row['PAY_YEAR'] !== $year) {
// Print the year in the left column so to speak, perhaps create a sublist, etc
// Set the year
$year = $row['PAY_YEAR'];
}
// Add month
// Do something with $row['PAY_MONTH'], perhaps add it to a sublist, again, depends on front end handling.
}
Option 2) Have it load the years, then the next level asynchronously.
SQL Query to get years:
SELECT DISTINCT
PAY_YEAR
FROM
india_salary_slip_details
WHERE
EMPLOYEE_ID = 34
ORDER BY
PAY_YEAR
SQL Query to get months given a year:
SELECT
PAY_MONTH
FROM
india_salary_slip_details
WHERE
EMPLOYEE_ID = 34
AND PAY_YEAR = (Whatever the year is)
ORDER BY
PAY_MONTH
The problem is your group by, you just want to order by year :
SELECT PAY_MONTH, PAY_YEAR, FROM india_salary_slip_details WHERE EMPLOYEE_ID = 34
ORDER BY PAY_YEAR
I am trying to create a PHP query to delete SQL table rows if the order_date column is a over a year old. I would also like a second query where table rows will be deleted if the same column is a day old.
To go more in depth, the order_date column is in my current table, tracking_orders, and was created using part of a query: order_date datetime NOT NULL DEFAULT GETDATE(),. The tracking_orders table currently looks like this:
order_date tracking_order account_id
Apr 7 2014 3:49PM 1 1
Apr 7 2014 3:51PM 2 1
The day I am asking this question is April 8th 2014, so I am trying to make a query to delete rows if the order_date data is Apr 7 2013, and another query to delete rows if the
order_date data is Apr 7 2014. Also, if the data is more than 1 year old, I would still like it to delete. For example, Apr 7 2012.
For a code example, I am looking for something like this:
$sql = 'DELETE * from tracking_orders WHERE order_date == DATE_SUB(getdate(), INTERVAL 1 YEAR)';
And something like this, to delete after one day:
$sql = 'DELETE * from tracking_orders WHERE order_date == DATE_SUB(getdate(), INTERVAL 1 DAY)';
Note: the above doesn't work because DATE_SUB is MySQL syntax, and I am working with MSSQL.
Thank you for any help. All help is greatly appreciated.
Try this:
DELETE from tracking_orders
WHERE DATEDIFF(dy,order_date, getdate()) = 1
OR DATEDIFF(yy,order_date, getdate()) > 1
The first condition in where checks for a difference of 1 day, and the second for a difference greater than 1 year. Note that this is going strictly by the calendar so the below will also return 1 even though time difference is less than 24 hours:
select datediff (dy, '2013-01-01 23:00:00.000', '2013-01-02 22:00:00.000')
To check for 24 hour difference only use DATEDIFF(hh,order_date, getdate()) = 1
I have a table on my php page populated with data from a MySQL query from a single table
The table looks like:
Location Jan Feb Mar etc… Total
Location1 5 13 7 25
Location2 10 10 6 26
Location3 22 1 7 29
Etc…
The ‘Total’ is calculated by the query using Sum ie SUM(IF(month = '1', 1,0)) AS 'jan', SUM(IF(month = '2', 1,0)) ASfeb, SUM(IF(month = '3', 1,0))
What I want are the totals for each column (Jan, Feb, Mar etc)
I can do this in PHP by adding the values as they are extracted but can I do it the query – and is there an advantage to doing so?
Thanks in advance for help rendered.
To me, this is a strange layout of a database, but I normally use a row based approach along these lines:
location | month | total |
loc1 | 1 | 3 |
loc2 | 1 | 4 |
loc1 | 2 | 7 |
etc...
which makes totals and the like MUCH easier to perform.
However, given you structure, you could either continue to do what you are doing or use a little trickery. If you are doing more work with it in PHP (aside from just the totals) you could easily do a concat() in SQL and get a preformatted string that is ready to be explode()-ed into an array. From there you can use all the wonderful array functions in PHP to get totals or anything else you like.
Edit: Righto, that makes some difference.
If you are using a normal row based approach to storing the data, you can probably make the database do all the work. If you need a query to get the individual months AND the totals, you can either do it in PHP of course, but you can also do a little trick like this:
select
month, // assuming 1-12 for example
sum(someData)
from
yourTable
where
someCondition=1
group by
month
union all
select
13 as month, // assuming 1-12 for example
sum(someData)
from
yourTable
where
someCondition=1
group by
month
This is handy if you have a DB that has loads of free CPU, but a webserver that is struggling or you have a very LARGE amount of data that needs to be tallied up for example. Just make the database do the crunching and return it as some specific number you can identify in your PHP code - months 1-12 will be normal, month 13 is the total.
Too hard to say, it depends on the rest of the code. What are you doing with the results? Just outputting them? How complex is the query?
In any case I would GROUP BY location, month ORDER BY month then loop the result rows in PHP to build the table. (If any month is missing in a location, nothing will be returned, so make sure to watch out for that.)
Im am selecting various things from a table. The problem is I only want to select them if they belong to the current year and the next year.
My table looks like this
Title Text Date
The date is formated like this 0000-00-00 and is in the format "date"
So the question is how can i select only items from only this year and the next?
Example: the year is 2012, I have items in my table that is old and i dont want them to show - I only want to select items from at the first 2012 1 January and last in this case 31 Dec 2013 current year 2012 + 1 year.
Thanks a lot for any help!
SELECT
*
FROM
table
WHERE
YEAR(date) = YEAR(CURDATE())
OR
YEAR(date) = YEAR(CURDATE()) + 1
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
SELECT
*
FROM
table
WHERE
date BETWEEN CONCAT(YEAR(CURDATE()),'-01-01') AND CONCAT(YEAR(CURDATE())+1,'-12-31')
As ugly as it looks, it allows your query to use index on date field.
Better idea is to create limiting dates in external PHP script, so that the query can use query cache.
If you only want to show items, that are no older than two years, you can do this:
SELECT
*
FROM
table
WHERE
date >= CURDATE() - INTERVAL 2 YEAR;