SQL query all register but select only one of one column [duplicate] - sql

This question already has answers here:
Get top 1 row of each group
(19 answers)
Closed 1 year ago.
Assume that I have one table looking like this:
ID
ClientID
Name
Country
1
JX100
John
Canada
2
JX100
John
Japan
3
JX690
Rob
EUA
4
PX301
Alice
France
And My query:
SELECT DISTINCT ClientID,Name,Country FROM CLIENTS
OUTPUT:
ClientID
Name
Country
JX100
John
Canada
JX100
John
Japan
JX690
Rob
EUA
PX301
Alice
France
I want to take that:
DESIRED:
ClientID
Name
Country
JX100
John
Canada
JX690
Rob
EUA
PX301
Alice
France
TL;DR
I just want to select one country for all Clients, I don't want to get repeated rows.

You can use row_number()over() with common table expression like below:
with cte as (
SELECT DISTINCT ClientID,Name,Country,row_number()over(partition by ClientID ,Name order by Country) rownumber FROM CLIENTS)
select * from cte where rownumber=1
Row_number()over(partition by ClientID ,Name order by Country) will generate a sequence for contries starting from 1 against each clientid and name. So when you will select rownumber=1 this query will select one country for a single clientid,name combination.

Related

SQL query to get only rows match the condition based on two separated columns under one 'group by'

The simple SELECT query would return the data as below:
Select ID, User, Country, TimeLogged from Data
ID User Country TimeLogged
1 Samantha SCO 10
1 John UK 5
1 Andrew NZL 15
2 John UK 20
3 Mark UK 10
3 Mark UK 20
3 Steven UK 10
3 Andrew NZL 15
3 Sharon IRL 5
4 Andrew NZL 25
4 Michael AUS 5
5 Jessica USA 30
I would like to return a sum of time logged for each user grouped by ID
But for only ID numbers where both of these values Country = UK and User = Andrew are included within their rows.
So the output in the above example would be
ID User Country TimeLogged
1 John UK 5
1 Andrew NZL 15
3 Mark UK 30
3 Steven UK 10
3 Andrew NZL 15
First you need to identify which IDs you're going to be returning
SELECT ID FROM MyTable WHERE Country='UK'
INTERSECT
SELECT ID FROM MyTable WHERE [User]='Andrew';
and based on that, you can then filter to aggregate the expected rows.
SELECT ID,
[User],
Country,
SUM(Timelogged) as Timelogged
FROM mytable
WHERE (Country='UK' OR [User]='Andrew')
AND ID IN( SELECT ID FROM MyTable WHERE Country='UK'
INTERSECT
SELECT ID FROM MyTable WHERE [User]='Andrew')
GROUP BY ID, [User], country;
So, you have described what you need to write almost perfectly but not quite. Your result table indicates that you want Country = UK OR User = Andrew, rather than AND
You need to select and group by, then include a WHERE:-
Select ID, User, Country, SUM(Timelogged) as Timelogged from mytable
WHERE Country='UK' OR User='Andrew'
Group by ID, user, country

SQL: How do you count the number of unique records?

I'm new to SQL and sorry if this q has been asked before - I couldn't phrase it properly.
Say I have a table that looks like this:
Name Call ID
Sally 1
Sally 2
Sally 3
Mike 4
Mike 5
Bob 6
Bob 7
I want to create a new table that looks like this:
Name No. of calls
Sally 3
Mike 2
Bob 2
Attempt
I assume I would do something like:
SELECT
Name,
COUNT(distinct Name) AS No. of Calls
FROM Table
Thanks.
You just need to group them and that's all.
SELECT
Name
COUNT(*) AS [No. of Calls]
FROM
Table
GROUP BY
Name
You're looking for GROUP BY:
SELECT Name, COUNT(*) AS 'No. of Calls'
FROM Table
GROUP BY NAME
ORDER BY COUNT(*) DESC

SQL: select values in table A which are not in table B (and the other way around)

I have a hypothetical Census information by areas (Districts) collected in two different years:
Year 1 Table
District | Name
----------------
1 | Paul
1 | John
2 | Max
2 | Aaron
3 | Michael
Year 2 Table
District | Name
1 | Paul
1 | John
1 | Michael
3 | Michael
I'd like two queries:
Query 1: List new people by District. Should return Michael in District 1
Query 2: List missed people by District. Should return Max and Aaron in District 2
I would do this using union all and aggregation. The following query returns the name/district combinations that appear only in one year, along with the specific year:
select district, name, min(yyyy)
from ((select 1 as yyyy, district, name from table1) union all
(select 2, district, name from table2)
) tt
group by district, name
having count(distinct yyyy) = 1;
Query 1 : List new people by District. Should return Michael in District 1
SELECT Name, District
FROM year2
WHERE (Name NOT IN
(SELECT Name
FROM year1
WHERE (District = year2.District)))
GROUP BY Name, District
Query 2: List missed people by District. Should return Max and Aaron in District 2
SELECT Name, District
FROM year1
WHERE (Name NOT IN
(SELECT Name
FROM year2
WHERE (District = District)))
GROUP BY Name, District
If further you need combined result just use union all

Retrieve highest value from sql table

How can retrieve that data:
Name Title Profit
Peter CEO 2
Robert A.D 3
Michael Vice 5
Peter CEO 4
Robert Admin 5
Robert CEO 13
Adrin Promotion 8
Michael Vice 21
Peter CEO 3
Robert Admin 15
to get this:
Peter........4
Robert.......15
Michael......21
Adrin........8
I want to get the highest profit value from each name.
If there are multiple equal names always take the highest value.
select name,max(profit) from table group by name
Since this type of request almost always follows with "now can I include the title?" - here is a query that gets the highest profit for each name but can include all the other columns without grouping or applying arbitrary aggregates to those other columns:
;WITH x AS
(
SELECT Name, Title, Profit, rn = ROW_NUMBER()
OVER (PARTITION BY Name ORDER BY Profit DESC)
FROM dbo.table
)
SELECT Name, Title, Profit
FROM x
WHERE rn = 1;

Select query which returns exect no of rows as compare in values of sub query

I have got a table named student. I have written this query:
select * From student where sname in ('rajesh','rohit','rajesh')
In the above query it's returning me two records; one matching 'rajesh' and another matching: 'rohit'.
But i want there to be 3 records: 2 for 'rajesh' and 1 for 'rohit'.
Please provide me some solution or tell me where i am missing.
NOTE: the count of result of sub query is not fix there can be many words there some distinct and some multiple occurrence .
Thanks
Your requirements are not clear, and I'll try to explain why.
Let's define table students
ID FirstName LastName
1 John Smith
2 Mike Smith
3 Ben Bray
4 John Bray
5 John Smith
6 Bill Lynch
7 Bill Smith
Query with WHERE clause:
FirstName in ('Mike', 'Ben', 'Mike')
will return 2 rows only, because it could be rewritten as:
FirstName='Mike' or FirstName='Ben' or FirstName='Mike'
WHERE is filtering clause that just says if existing row satisfy given conditions or not (for each of rows created by FROM clause.
Let's say we have subquery that returns any number of non distinct FirstNames
In case if SQ contains 'Mike', 'Ben', 'Mike' using inner join you can get those 3 rows without problem
Select ST.* from Students ST
Inner Join (Select name from …. <your subquery>) SQ
On ST.FirstName=SQ.name
Result will be:
ID FirstName LastName
2 Mike Smith
2 Mike Smith
3 Ben Bray
Note data are not ordered by order of names returning by SQ. If you want that, SQ should return some ordering number, eg.:
Ord Name
1. Mike
2. Ben
3. Mike
In that case query should be:
Select ST.* from Students ST
Inner Join (Select ord, name from …. <your subquery>) SQ
On ST.FirstName=SQ.name
Order By SQ.ord
And result:
ID FirstName LastName
2 Mike Smith (1)
3 Ben Bray (2)
2 Mike Smith (3)
Now, let's se what will happen if subquery returns
Ord Name
1. Mike
2. Bill
3. Mike
You will end up with
ID FirstName LastName
2 Mike Smith (1)
6 Bill Lynch (2)
7 Bill Smith (2)
2 Mike Smith (3)
Even worse, if you have something like:
Ord Name
1. John
2. Bill
3. John
Result is:
ID FirstName LastName
1 John Smith (1)
4 John Bray (1)
5 John Smith (1)
6 Bill Lynch (2)
7 Bill Smith (2)
1 John Smith (3)
4 John Bray (3)
5 John Smith (3)
This is an complex situation, and you have to clarify precisely what requirement is.
If you need only one student with the same name, for each of rows in SQ, you can use something like SQL 2005+):
;With st1 as
(
Select Row_Number() over (Partition by SQ.ord Order By ID) as rowNum,
ST.ID,
ST.FirstName,
ST.LastName,
SQ.ord
from Students ST
Inner Join (Select ord, name from …. <your subquery>) SQ
On ST.FirstName=SQ.name
)
Select ID, FirstName, LastName
From st1
Where rowNum=1 -- that was missing row, added later
Order By ord
It will return (for SQ values John, Bill, John)
ID FirstName LastName
1 John Smith (1)
6 Bill Lynch (2)
1 John Smith (3)
Note, numbers (1),(2),(3) are shown to display value of ord although they are not returned by query.
If you can split the where clause in your calling code, you could perform a UNION ALL on each clause.
SELECT * FROM Student WHERE sname = 'rajesh'
UNION ALL SELECT * FROM Student WHERE sname = 'rohit'
UNION ALL SELECT * FROM Student WHERE sname = 'rajesh'
Try using a JOIN:
SELECT ...
FROM Student s
INNER JOIN (
SELECT 'rajesh' AS sname
UNION ALL
SELECT 'rohit'
UNION ALL
SELECT 'rajesh') t ON s.sname = t.sname
just because you've got a criteria in there two times doesn't mean that it will return 1 result per criteria. SQL engines usually just use the unique criteria - thus, from your example, there will be 2 criteria in IN clause: 'rajesh','rohit'
WHY do you need to return 2 results? are there two rajesh in your table? they should BOTH return then. You don't need to ask for rajesh twice for that to happen. What does your data look like? What do you want to see returned?
Hi i am query just as you give above and it give me all data that matches in the condition of in clause. just like your post
select * from person
where personid in (
'Carson','Kim','Carson'
)
order by FirstName
and its give me all records which fulfill this Criteria