Need help to make sql query to compare data column-wise - php

I have a mysql table which collects daily sales data (date, sale, gst etc). I need a select statement to compare daily sales for any given date with same date last year and year before, to see the how much we made on that day in previous years.
To give an idea of how the output table will look, I have an example table in jsfiddle.
And here is the sql table data in sqlfiddle.
I tried this statement:
SELECT * FROM sales_chc WHERE MONTH(sale_date) = '1'
It of course gives me the filtered results that I want but I couldn't figure out how to display the results in the give table example.

By changing year and month in the WHERE statement, you can get a report for whatever month/year combination you need.
SELECT sn.sale_date AS SaleY0 , sn.EFTPOS AS EFTPOSY0, sn.total AS totalY0,
s1.sale_date AS SaleY1 , s1.EFTPOS AS EFTPOSY1, s1.total AS totalY1,
s2.sale_date AS SaleY2 , s2.EFTPOS AS EFTPOSY2, s2.total AS totalY2
FROM sales_chc sn
LEFT JOIN sales_chc S1
ON s1.sale_date=(sn.sale_date -INTERVAL 1 YEAR)
LEFT JOIN sales_chc S2
ON s2.sale_date=(sn.sale_date -INTERVAL 2 YEAR)
WHERE YEAR(SN.sale_date)=2016 AND MONTH(SN.sale_date)=1
SQL fiddle

Related

Get Last Payment From A User in SQL

I have this table
I am trying to get the sum of principal + interest from the last transaction date. Column 4. is the last transaction performed - [No column name] is the transaction date
What I have tried so far:
select sum(h.principal+h.interest) as amt_paid, MAX(h.trx_date)
from Loanhist h WHERE h.ac_no = '$id' and h.trx_type='LP'
GROUP BY principal, interest
The test data generation is for Oracle, but you should easily be able to adapt it. The actual query will work on SQL server. You'll need to use an approach like this if the account can post more than one transaction in a day. Otherwise the 'LIMIT/TOP 1' approaches in the other answers will work fine.
CREATE GLOBAL TEMPORARY TABLE balances
( ac_no CHAR(100),
principal FLOAT,
interest FLOAT,
tranDate DATE
)
ON COMMIT PRESERVE ROWS;
INSERT INTO balances VALUES (1,123.123,.456,DATE '2017-01-01');
INSERT INTO balances VALUES (1,100,.456,DATE '2017-01-02');
INSERT INTO balances VALUES (1,200,.1,DATE '2017-01-02');
INSERT INTO balances VALUES (2,200,.1,DATE '2017-01-02');
INSERT INTO balances VALUES (2,300,.1,DATE '2017-01-02');
SELECT SUM
( CASE WHEN tranDate = max_tran_date
THEN principal + interest
ELSE 0
END
) AS tranSum
FROM (SELECT sub.*,
MAX(tranDate) OVER() AS max_tran_date
FROM balances sub
) BAL;
Your question is not really clear. But if you just want to get the last transaction performed by the user, the best thing to do will be to rely on IDs instead of dates.
SELECT TOP 1 * FROM Loanhist h WHERE h.trx_type='LP' ORDER BY h.ac_no DESC
try to use LIMIT keyword.For Example, Select * from table name where condition LIMIT 1.It will return first row
Try this:
SELECT TOP 1 sum(h.principal+h.interest) as amt_paid, h.trx_date
FROM Loanhist h WHERE h.ac_no = '$id' AND h.trx_type='LP'
ORDER BY h.ac_no DESC;

Mysql get max row and min row from group of each row

I have MySQL table with employees attendance. first row of a day of employee treating as in time and last row of a day of employee treating as out time. I am trying to select first and last (min time and max time) from attendance table. It should give me two row sets. but my query not giving me as i expecting the result.
Table (Attendance)
My Query
select *, min(attdate) as intime, max(attdate) as outtime from attendance where empid=1
But above query not giving me as expected result. My output should be in below image. Please suggest me the query or give me hint to achieve given output.
this can be done by sub queries in where conditions.
SELECT * FROM attendance AS c WHERE empid=1 and (
attdate=( select min(attdate) from attendance where attendance.empid=c.empid )
or attdate=( select max(attdate) from attendance where attendance.empid=c.empid )
);
Unfortunately, MySQL doesn't offer window functions, so it's a bit more difficult here. You can use exists :
Select * from yourtable t
Where not exists (select 1 from yourtable s
Where t.empid = s.empid and
(s.attndate < t.attndate or s.attndate > t.attndate))
Though it seems you need to add another condition t.date = s.date unless you have only 1 day records stored there

Order Mysql query by Name and other fields

I have a question about MySQL. I have a Table with this fields:
WorkerName
Date
HoursWorked
Ok, if I do this Query:
SELECT WorkerName, Date, HoursWorked, SUM(HoursWorked) FROM myTable GROUP BY WorkerName
I have the field grouped by the Worker Name BUT with a only row. I want to show all days worked by this Worker in the same row, and the other Worker in another row.
In PHP actually have a While that shows all days worked, but only shows the Hours of the first day sorted.
You can use GROUP_CONCAT aggregate function:
SELECT
WorkerName,
GROUP_CONCAT(Date) AS dates_worked,
SUM(HoursWorked)
FROM
myTable
GROUP BY
WorkerName

Finding null field with two data tables and date table joined

I am trying to figure out how to do this SQL query, but I'm at a loss. I think I am getting in over my head.
I have three tables:
1. datetable, which contains lists of month/year up to year 2020. column is 'thedate'
2. A table containing a list of lectures. A date() field is one column, named "month"
3. A log table, which contains individual rows of data on a month to month basis. i.e Each user has their own row of data for each month of the year.
I would like to take table #2, find if there is a lecture assigned for month x, then take table #3, find the row which corresponds to month x and particular user, then see if column 'hopkins' (a part of table 3) is null or not. I hope this makes a little bit of sense. I've figured out how to use the datetable to find missing rows in table #2, but I haven't figured out how to do this above.
Thanks!
I think you just want a left join from eval to hopkins and then a test on the field:
select e.uid,
max(case when h.name is null then 0 else 1 end) as isInHopkins
from eval e left outer join
hopkins h
on year(e.month) = year(h.month) and
month(e.month) = month(h.month)
group by e.uid;
If the hopkins.id is supposed to related to the user, then you would want to add and e.uid = h.id to the on clause.
If this doesn't give you what you want, then please edit your question to provide sample results for the SQL Fiddle data.

Select Mulitple Records based on One record's column value

I have a table which contains related records (multiple revisions of the same record). Each record has a string field that resembles a date (date, time, and microtime). I want to select all records that are older than a specific date. If a record has a related record newer than the specific date, I do not want to select any of those related records. Any ideas for that select statement? Eventually, it will be a REMOVE statement.
Edit: Some Sample Rows
id shared_id date type other_data...
1 2 2010-01-01 01:02:03.1234567 original ...
2 3 2010-01-15 11:12:03.1234733 original ...
3 2 2010-02-01 03:04:04.5465654 amendment ...
If my cut-off date was "2010-01-31", I would want to select id #2 only because id #1 has an amendment newer than the cut-off date.
I found this link helping me generate the select statement.
SELECT DISTINCT T.shared_id,T.date,T.id
FROM table T WHERE T.date = (
SELECT MAX( date ) FROM table WHERE shared_id = T.shared_id )
AND T.date < 'my_cut_off_date_string'
This seems to work for me. Thanks for everyone's help.
Maybe you can try the DATEDIFF() function, check this out:
Link 1
Or this one: Link 2
Or maybe you can try the classic query (SELECT FROM table WHERE data <= anotherdata), but in this case you need to convert both data in timestamp format
DELETE from tablename where relatedField = 'relatedValue' AND dateField <= dateToDeleteFrom
Something along those lines should do what you need it to do, if I understand your scenario. If you provide a sample data set I can adjust the statement to more accurately represent your need, but I think this is a good starting point.
HTH,
Jc

Categories