Remove Duplicate Row Except The Last One - php

I have this table on MySql:
Table1
ID CODE USER NUMBER ADJUSTMENT ADJUST_DATE
1 abc Frank 10245 1 2015/04/20
2 def Jonathan 25410 0 2015/04/21
3 ghi Karen 55214 3 2015/05/05
4 abc Frank 10245 2 2015/04/21
5 abc Frank 10245 4 2015/04/22
I would like to remove the duplicated data and leave the last entry by date:
ID CODE USER NUMBER ADJUSTMENT ADJUS_DATE
2 def Jonathan 25410 0 2015/04/21
3 ghi Karen 55214 3 2015/05/05
5 abc Frank 10245 4 2015/04/22
CODE, USER, NUMBER, ADJUSTMENT, ADJUS_DATE are 'Unique'
I need to create a temporary table with the result because I need all the records.

Generate a subset of the max date grouped by like values in columns and join back to the base set...
SELECT A.ID, A.Code, A.user, A.Number, A.Adjustment, A.Adjust_date
FROM table1 A
INNER JOIN (SELECT Code, User, Number, max(adjust_date) mDate
FROM table1 group by Code, User, Number) B
on A.code = B.code
and A.user = B.User
and A.Number = B.Number
and A.Adjust_date = B.mdate

Related

Assign Text (Label) to values in SQL Query Result

All data in my tables are in numeric format. For example,
class sex subject medium
5 1 1 1
1 1 1 2
4 3 3 1
5 1 3 2
1 1 3 1
3 1 2 2
1 2 2 2
Other Table contains Description to each value for each table. For Example,
Table Column value text
Student class 1 1ST
Student class 2 2ND
Student class 3 3RD
Student class 4 4TH
Student class 5 5TH
Student sex 1 male
Student sex 2 female
Student sex 3 creator
Student medium 1 English
Student medium 2 Hindi
I am trying to provide a text (label to each column when user queries). I have been able to do it for one column. For example,
SELECT class, sex, avg(total_marks) as total
FROM (
SELECT value, text as sex
FROM Label
WHERE table_name = 'Student' and
Column = 'class' or
) AS Label INNER JOIN Student on value = class
GROUP BY class, sex
This results in
class sex total
1ST 1 64.80
1ST 2 59.66
2ND 1 78.96
2ND 2 96.97
3RD 1 52.67
3RD 2 81.77
4TH 1 61.99
4TH 2 99.78
5TH 1 72.90
5TH 2 70.59
Instead of 1 / 2 /3 in sex I want to show male, female and creator. Select and Group by columns can be more than 4 at times. I am using MySql and PHP Laravel to do this.
I guess I found the answer. Any suggestions are most welcome.
SELECT T1.class, T2.sex, SUM(weight)
FROM household_characteristics
INNER JOIN (SELECT value_label_name as code, value_label_value FROM labels
WHERE table_name = 'Student' and columns = 'class' ) AS T1 ON T1.code = Student.class
INNER JOIN (SELECT value_label_name as code, value_label_value FROM labels
WHERE table_name = 'Student' and columns = 'sex' ) AS T2 ON T2.code = Student.sex
GROUP BY class, sex

Mysql select multiple count giving wrong values

I'm trying to find a patient's appointments and messages count. My table records are like below 3 table patient, appointments and messages
Patient table
pid fname lname
1 john sid
2 rother ford
3 megan rough
4 louis kane
appointments table
id pid appointment_date
1 1 2015-08-04
2 2 2015-08-05
3 1 2015-08-06
4 1 2015-08-07
5 3 2015-08-07
6 2 2015-08-08
7 4 2015-08-13
8 1 2015-08-12
Messages table
id pid description message_date
1 2 join 2015-08-04
2 2 update 2015-08-05
3 3 join 2015-08-05
4 4 update 2015-08-10
5 3 test 2015-08-07
So if write query to find counts i'm getting wrong values
SELECT pd.fname,pd.lname , pd.pid, COUNT( a.id ) AS app_cnt, COUNT( m.id ) AS mes_cnt
FROM patient pd
LEFT OUTER JOIN appointments a ON a.pid = pd.pid
LEFT OUTER JOIN messages m ON m.pid = pd.pid
GROUP BY pd.pid
ORDER BY pd.pid
fname lname pid app_cnt mes_cnt
john sid 1 4 0
rother ford 2 4 4
megan rough 3 2 2
louis kane 4 1 1
Here pid 1 have 4 appointments and 0 messages, pid 2 have 2 appointments and 2 messages but getting wrong values.
Can someone please help to resolve this issue. I'm not interested in writing sub queries for this.
Functionality looks simple but I'm really facing problem for writing query.
Anymore suggestions please.
After thoroughly analysing your problem and tables, It cannot be done directly using simple query as LEFT OUTER JOIN is returning some superfluous records, that's why to filter it, you will have to use temporary table and modify the query as:
Select temp.fname, temp.lname, temp.pid, a_count, count(m.pid) as m_count from
(SELECT fname,lname,pd.pid, count(a.pid) as a_count
FROM patients pd
LEFT OUTER JOIN appointments a ON a.pid = pd.pid group by pd.pid) temp
LEFT OUTER JOIN messages m ON m.pid = temp.pid
group by temp.pid
Explanation:
It will join patients and appointments table and group them by pid so that messages from message table do not repeat for each patients.pid.
The wrong result is as a result of left outer join as it is giving wrong results for this query
SELECT *
FROM patients pd
LEFT OUTER JOIN appointments a ON a.pid = pd.pid
LEFT OUTER JOIN messages m ON m.pid = pd.pid
Since we need to limit the results of first two joins, hence temporary table is necessary.

Return all the rows even the joined table has empty results

In my table 1 I have something like this
name | age
George 42
Bob 30
Ken 23
In my table 2, I have something like this, this is where i store votes for each person.
name | votes |
George 1
Ken 1
George 1
George 1
Ken 1
My goal is to combine the 2 tables, and return all the rows in table 1 even it doesn't exist in table 2.
Desire results:
name | age | total_votes
George 42 3
Bob 30 0
Ken 23 2
But instead I get:
name | age | total_votes
George 42 3
Ken 23 2
I have tried something like this
SELECT `table_1`.*, coalesce(COUNT(`table_2`.votes), 0) AS total_votes
FROM `table_1`
LEFT JOIN `table_2`
ON `table_1`.name = `table_2`.name
You can do one of these:
1) Use Right Join instead of current Left Join.
Or
2) Exchange table1 and table2 places in your join expression, like:
FROM table_2
LEFT JOIN table_1
Try this. This works in MS Access , I think this will work on your's too just convert the query to SQL:
SELECT Table1.name, First(Table1.age) AS age, Count(Table2.Votes) AS totalVotes
FROM Table1 LEFT JOIN Table2 ON Table1.name = Table2.name
GROUP BY Table1.name;
Left Join table1 to table2 so that all entry from table1 , even if its is corresponding data is null, will be included. GROUP BY your query by name so that votes will be counted by name .

Query and table - MAX and Join

Still very new to all of this so bear with me.
Have 3 tables
table 1: member
Mem_index, Mem_name
1 joe
2 Mark
Table 2: Course
Course_index, Course_Name
1 Math
2 Reading
Table 3 : data
Data index,Member,Course,Score
1 1 1 85
2 1 2 75
3 2 1 95
4 1 2 65
SO what I would like to do is create a table:
Do a query and gather all of the courses, find the max score for each course and attribute the member name to it.
Table result should look like:
Course, Max score,name
Math 95 Mark
Reading 75 Mark
I can do the query individually but unsure of how to loop it and then propogate the data into the table.
How about this query for SQL?
SELECT c.course_name, MAX( d.score ), m.mem_name
FROM members m
JOIN data d on m.mem_id = d.member
JOIN course c on c.course_id = d.course
GROUP BY d.course
ORDER BY d.score, m.mem_name, c.course_name
Not sure if the field names match up but you get the idea - tested this in sql with some dummy data.
Data
Index Member Course Score
1 1 1 60
1 1 1 85
Course
course_id course_name
1 Math
2 English
3 Science
Members
mem_id mem_name
1 Mark
2 James
You will get the following
Course Name Score Member
Math 85 Mark
Try this query :
SELECT c.course_Name , MAX(d.score),m.mem_name
FROM data d
JOIN course c ON d.course=c.course_index
JOIN members m ON m.mem_index = d.member
GROUP BY d.course
ORDER by MAX(d.score) DESC

Result display problem in php and mysql

A B C
P_id | name | add P_id | t_id t_id | paper
----------------- -------------- ------------------
1 sam ca 1 1 1 asdxa
2 john de 2 1 2 dgfv
3 sam jk 3 2 3 decgf
4 sam ca 4 3 4 ergvtr
Now I can easily make a search for Name 'sam' in Table A group by name, add. and It shows me result like,
sam ca
sam jk
I am using php and mysql. I want to do some additional task in this:-
--> Totalcount for the rows..Like
sam ca 2
sam jk 1
(I am not taking P_id here... just focus on name and add.)
--> Make a link on 2 and 1 (above). so if I click on it. It should displays the related papers on another html page from table C.
example: if I click on 2... then it should display asdxa and decgf.
--> Totalcount for the rows..Like
SELECT `name`, `add`, count(`add`) FROM `A` WHERE (`name` = 'sam') GROUP BY `add`;
As for the linking, you just link to the page with that ID, and have your php script get the data from the given id in the C table.
To select all matching occurences while searching for a name:
SELECT `A`.`name` AS name, `A`.`P_id` AS aid, `C`.`t_id` AS cid, `C`.`paper` AS paper
FROM `A` , `C`
WHERE (
`A`.`name` = 'sam'
)
AND (
`A`.`P_id` = `C`.`t_id`
)
result:
name aid cid paper
sam 1 1 qwertyui
sam 3 3 zxcvbn
sam 4 4 uytrewq
sam 5 5 hfdsa
Which matches the test tables I did in my local environment
Try to use for the first task
$pdo = new PDO(....);
$result = $pdo->query('SELECT name, add, count(*) from table where name='sam' group by add;')->fetchAll();
if ($result) {
foreach($result as $row) {
......
}
}
//second
$sql = 'select paper from tableA a inner join TableB b on a.P_id=b.P_id inner join Tablec c inner join b.t_id = c.t_id where a.p_id=2';
//repeat previous statements

Categories