SQL Server table data retrieval - sql

I have attended an interview recently, and the interviewer asked me this question:
UserId UserName
1 Name1
1 Name2
2 Name3
Here he wants me to retrieve either Name1 or Name2 using where condition?
How can I get the result?
I wrote like
select Username
from Users
where Username = 'Name1' or Username = 'Name2'
but here both the conditions are satisfied so two records are returned... What will be the query to retrieve the data?

I think you mean something like this:
SELECT UserName FROM Users
WHERE UserName IN(NAME1, NAME2)
LIMIT 1
That would sort of randomly select the first one you come across (out of NAME1 and NAME2). I'm assuming that you don't have to select a specific one, and that there aren't more instances of the names that also need to get selected, all as per your example.

Related

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.

SQL Select statement separate values into two columns

I have string value in the column Username.
Sample usernames:
USERNAME
--------
foobar123
john
smith23
steve
peter
king213
The user names with numbers at the end means that these users are no longer active. I want to separate these usernames into two columns Active and Not_Active in one Select Statement since i'll be using these for reports purposes.
Result should be:
Active Not_Active
john foobar123
steve smith23
peter king213
Query:
SELECT
Username,
(
CASE Username
WHEN '%[0-9]%' THEN 'Not'
ELSE 'Active'
END
)
FROM
Users;
I tried Case but I don't know how to get the username value.
Expanding on my comment reply to your original posting, you don't want the data in the same output result-set; instead you will want two result sets (i.e. two tables), each with the different criteria.
Note that you cannot use LIKE string matching (%) with the WHEN statement in SQL. You have to use it in a CASE WHEN statement (one without a "switch" expression)
-- Result set one: Active users
SELECT
UserName
FROM
Users
WHERE
UserName NOT LIKE '%[0-9]';
-- Result set two: Inactive users
SELECT
UserName
FROM
Users
WHERE
UserName LIKE '%[0-9]';
If you really want, you can combine these two queries into a single result-set with the data in different columns. This would be done by adding a ROW_NUMBER() column to each intermediate table, then doing a FULL OUTER JOIN on ROW_NUMBER(), however the output result would be meaningless and painful to iterate over in any consuming client code.
Another option might be a single result-set, with a computed IsActive column:
SELECT
UserName,
( CASE WHEN UserName NOT LIKE '%[0-9]' THEN 1 ELSE 0 END ) AS IsActive
FROM
Users
...which would be considerably easier to process in any consuming code.
this format of saving data is quite useful in this one column holds username and other holds status of the user
select username,
case username
when '%[0-9]% then inactive
else active
end as user_status
from table_1
username user_status
john active
john123 inactive

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

SQL get differences in one column by ID

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.

Access 2003/2007 : Query to find average of one text field grouped by another in table

So lets say I have a table that looks something like this:
ItemName ProductType
----------------------------------------------------------
Name1 Type1
Name2 Type1
Name3 Type1
Name4 Type2
Name5 Type3
and so on for thousands of records. I want a sql statement to find the average number of Names per Types. I want to use it in vba, behind a form.
How would I go about this? I have the sneaking suspision that this is something simple that is escaping me right now.
EDIT: Sorry....a little unclear. I mean in a table like fashion, have the types listed out with a count for each of the relative Names
Averages
Type Count of Names
-------------------------------------------
Type1 5
Type2 6
so basically see how many names applicable to types, what Inner Select statement should I use to accomplish this?
Thanks
Justin
select avg( c ) from
( select ProductType, count( ItemName ) c
from myTable
group by ProductType )