SQL get differences in one column by ID - sql

It's hard for me to word what I want which is why I've had trouble researching this issue. What I want is to look at a table by id and see if another column changes:
id name
---- ------
1 Al
2 Mia
1 Al
2 Jean
In the example, I don't care about id 1 because the name always stayed as Al but I care about id 2 because there is a record with the name Mia but then, that id 2 also has a record with the name Jean. I was thinking of using group by somehow but that doesn't work. Any ideas?

Try this:
SELECT id
FROM mytable
GROUP BY id
HAVING MIN(name) <> MAX(name)
This will select all ids having at least two different values.

Related

selecting duplicate columns in psql then sorting by row id

I have tried searching the web and whilst there are plenty of answers for finding duplicates, I am yet to stumble on one that allows me to find all the duplicates within a column (i.e where the same 'name' occurs more than once) and then only select the lowest row id (which would be the first duplicate name entered).
So the table's description (inserted from a file):
create table customer(id int, name varchar,)
id| name
1 | Darren
2 | Mark
3 | Julie
4 | Mark
5 | Julie
The query:
CREATE VIEW AS
SELECT COUNT(name), name
FROM customer
GROUP BY name
HAVING COUNT(name) > 1
Result (the order is never guaranteed, I want Mark to always come first as he has the lowest id):
Julie
Mark
Now the issue is, if i select id I have to include it in the group by. Doing that means no duplicate columns get selected as there wont be any since ever id is unique. And without selecting id I cant ORDER BY desc.
I hope I am clear, if not I can re-word or supply more information.
Please try this? Nested query. Basically the SELECT/GROUP is called. On the outside, we get the information selected and sort it.
CREATE VIEW AS
SELECT CNT_NAME, NAME
FROM
(
SELECT COUNT(name) CNT_NAME, name, min(id) min_id
FROM customer
GROUP BY name
HAVING COUNT(name) > 1
) AS alias
ORDER BY MIN_ID

Selecting from table where a name appears twice

I want to select from a table where a name appears twice.
For example I have a table like this,
ID Name
---- ------
1 Jane John
2 Kevin Smith
3 Jane John
What I want is for the output to show where Jane John appear twice so it should look something like this:
ID Name
---- ------
1 Jane John
3 Jane John
I tried looking around on stackoverflow but couldn't find an exact and easy answer.
I'm using oracle SQL Developer.
You ask for a record that appears twice. If a row appears three times it won't show unless you modify the having clause as commented.
SELECT id
,NAME
FROM tablen
WHERE NAME IN (
SELECT NAME
FROM TableN n
GROUP BY (NAME)
HAVING counT(NAME) = 2 --Use >1 instead of =2 for more than one record
)
EDIT
I'll add a new solution in regard to your last comment.
As you can only ask for one field in IN() I'll use a special character or string making sure it does not belongs to valid values in any field.
Look at this: http://sqlfiddle.com/#!6/2af55/3
SELECT id
,NAME
,name2
FROM tablen
WHERE concat(NAME,'=',name2) IN (
SELECT concat(NAME,'=',name2)
FROM TableN n
GROUP BY concat(NAME,'=',name2)
HAVING count(concat(NAME,'=',name2)) = 2
)
Note I wrote this thinking in SQL Server, not sure if concat function works as well in Oracle or look for an alternative.

Querying SQL table with different values in same column with same ID

I have an SQL Server 2012 table with ID, First Name and Last name. The ID is unique per person but due to an error in the historical feed, different people were assigned the same id.
------------------------------
ID FirstName LastName
------------------------------
1 ABC M
1 ABC M
1 ABC M
1 ABC N
2 BCD S
3 CDE T
4 DEF T
4 DEG T
In this case, the people with ID’s 1 are different (their last name is clearly different) but they have the same ID. How do I query and get the result? The table in this case has millions of rows. If it was a smaller table, I would probably have queried all ID’s with a count > 1 and filtered them in an excel.
What I am trying to do is, get a list of all such ID's which have been assigned to two different users.
Any ideas or help would be very appreciated.
Edit: I dont think I framed the question very well.
There are two ID's which are present multiple time. 1 and 4. The rows with id 4 are identical. I dont want this in my result. The rows with ID 1, although the first name is same, the last name is different for 1 row. I want only those ID's whose ID is same but one of the first or last names is different.
I tried loading ID's which have multiple occurrences into a temp table and tried to compare it against the parent table albeit unsuccessfully. Any other ideas that I can try and implement?
SELECT
ID
FROM
<<Table>>
GROUP BY
ID
HAVING
COUNT(*) > 1;
SELECT *
FROM myTable
WHERE ID IN (
SELECT ID
FROM myTable
GROUP BY ID
HAVING MAX(LastName) <> MIN(LastName) OR MAX(FirstName) <> MIN(FirstName)
)
ORDER BY ID, LASTNAME

Can IBM DB2 return a 0 (zero) when no records are found?

for example :
I have a table with student ID and student grades
-----------------------
ID | grades
-----------------------
1 | 80
2 | 28
-----------------------
I want to get 0 when I query about ID = 3
can I do that ?
like select grades from student where id = 3 .
I want to get 0 because ID is not in the table
Run a select command with the reserved function called count:
select count(*) from STUDENT.GRADES where ID=3
It should be just like that.
Maybe this will do what you want:
SELECT ID, MAX(Grades)
FROM (SELECT ID, Grade FROM Students WHERE ID = 3
UNION
VALUES (3, 0) -- Not certain of syntax here
)
GROUP BY ID
The basic idea is that students present in the table will have two rows and the MAX will pick their proper grade (assuming that there are no circumstances where the grade is coded as a negative value). Students that are not represented will have just the one row with a grade of 0. The repeated 3 is the ID of the student being sought.
Have fun chasing down the full syntax. I started at Queries in the DB2 9.7 Information Centre, but ran out of patience before I got a good answer — and I don't have DB2 to experiment on. You might need to write SELECT ID, Grades FROM VALUES (3, 0), or there might be some other magical incantation that does the job. You could probably use SELECT 3 AS ID, 0 AS Grades FROM SYSIBM.SYSTABLES WHERE TABID = 1, but that's a clumsy expression.
I've kept with the column name Grades (plural) even though it looks like it contains one grade. It is depressing how often people ask questions about anonymous tables.

How do I make a query for if value exists in row add a value to another field?

I have a database on access and I want to add a value to a column at the end of each row based on which hospital they are in. This is a separate value. For example - the hospital called "St. James Hospital" has the id of "3" in a separate field. How do I do this using a query rather than manually going through a whole database?
example here
Not the best solution, but you can do something like this:
create table new_table as
select id, case when hospital="St. James Hospital" then 3 else null
from old_table
Or, the better option would be to create a table with the columns hospital_name and hospital_id. You can then create a foreign key relationship that will create the mapping for you, and enforce data integrity. A join across the two tables will produce what you want.
Read about this here:
http://net.tutsplus.com/tutorials/databases/sql-for-beginners-part-3-database-relationships/
The answer to your question is a JOIN+UPDATE. I am fairly sure if you looked up you would find the below link.
Access DB update one table with value from another
You could do this:
update yourTable
set yourFinalColumnWhateverItsNameIs = {your desired value}
where someColumn = 3
Every row in the table that has a 3 in the someColumn column will then have that final column set to your desired value.
If this isn't what you want, please make your question clearer. Are you trying to put the name of the hospital into this table? If so, that is not a good idea and there are better ways to accomplish that.
Furthermore, if every row with a certain value (3) gets this value, you could simply add it to the other (i.e. Hospitals) table. No need to repeat it everywhere in the table that points back to the Hospitals table.
P.S. Here's an example of what I meant:
Let's say you have two tables
HOSPITALS
id
name
city
state
BIRTHS
id
hospitalid
babysname
gender
mothersname
fathername
You could get a baby's city of birth without having to include the City column in the Births table, simply by joining the tables on hospitals.id = births.hospitalid.
After examining your ACCDB file, I suggest you consider setting up the tables differently.
Table Health_Professionals:
ID First Name Second Name Position hospital_id
1 John Doe PI 2
2 Joe Smith Co-PI 1
3 Sarah Johnson Nurse 3
Table Hospitals:
hospital_id Hospital
1 Beaumont
2 St James
3 Letterkenny Hosptial
A key point is to avoid storing both the hospital ID and name in the Health_Professionals table. Store only the ID. When you need to see the name, use the hospital ID to join with the Hospitals table and get the name from there.
A useful side effect of this design is that if anyone ever misspells a hospital name, eg "Hosptial", you need correct that error in only one place. Same holds true whenever a hospital is intentionally renamed.
Based on those tables, the query below returns this result set.
ID Second Name First Name Position hospital_id Hospital
1 Doe John PI 2 St James
3 Johnson Sarah Nurse 3 Letterkenny Hosptial
2 Smith Joe Co-PI 1 Beaumont
SELECT
hp.ID,
hp.[Second Name],
hp.[First Name],
hp.Position,
hp.hospital_id,
h.Hospital
FROM
Health_Professionals AS hp
INNER JOIN Hospitals AS h
ON hp.hospital_id = h.hospital_id
ORDER BY
hp.[Second Name],
hp.[First Name];