Reputation: 91
I got a table like
ID NAME TL_NUM TL_NAME MANAGER_NUM
===============================================
1 F-23 2 T-2 1
2 B-23 3 T-3 2
3 F-24 2 T-2 1
4 F-25 1 T-1 2
5 F-26 2 T-2 2
6 F-27 1 T-1 2
Now I would like to get a result set as follows
TL_NUM TL_NAME MANAGER_NUM
================================
2 T-2 1
3 T-3 2
1 T-1 2
2 T-2 2
I tried using this following query
select DISTINCT TL_NUM, TL_NAME,MANAGER_NUM
from dataTable
It gives me a correct result set when use this query but not the above one:
select DISTINCT TL_NUM, TL_NAME
from dataTable
but it is not returning correct 'MANAGER_NUM' in my result set. Can anyone let me in know what the exact issue is, I believe it is because of DISTINCT?
Upvotes: 1
Views: 611
Reputation: 1
check out my fiddle below:
DECLARE @tmp TABLE ( ID INT,NAME NVARCHAR(100),TL_NUM INT,TL_NAME NVARCHAR(100),MANAGER_NUM INT)
INSERT INTO @tmp
VALUES
(1, 'F-23', 2, 'T-2', 1)
,(2, 'B-23', 3, 'T-3', 2)
,(3, 'F-24', 2, 'T-2', 1)
,(4, 'F-25', 1, 'T-1', 2)
,(5, 'F-26', 2, 'T-2', 2)
,(6, 'F-27', 1, 'T-1', 2)
SELECT DISTINCT t.TL_NUM ,t.TL_NAME ,t.MANAGER_NUM
FROM @tmp AS t
ORDER BY t.MANAGER_NUM
,t.TL_NAME DESC
Upvotes: 0
Reputation: 3756
After testing, it does return the correct values - are you looking at the values correctly? Here is a test script for creating a working version of the table:
CREATE TABLE #dataTable (id int identity, Name varchar(10), TL_NUM smallint, TL_NAME varchar(10), MANAGER_NUM smallint)
INSERT INTO #datatable (Name, TL_NUM, TL_NAME, MANAGER_NUM)
VALUES
('F-23', 2, 'T-2', 1),
('B-23', 3, 'T-3', 2),
('F-24', 2, 'T-2', 1),
('F-25', 1, 'T-1', 2),
('F-26', 2, 'T-2', 2),
('F-27', 1, 'T-1', 2)
Then I used your query:
select DISTINCT TL_NUM, TL_NAME ,MANAGER_NUM
from #dataTable
And got this return value set:
---------------------------------
|TL_NUM |TL_NAME |MANAGER_NUM|
---------------------------------
|1 |T-1 |2 |
|2 |T-2 |1 |
|2 |T-2 |2 |
|3 |T-3 |2 |
---------------------------------
The primary difference is the order of the returned rows, but they are returned with correct values.
Upvotes: 0
Reputation: 21
You can do like this:
CREATE TABLE TAB1 ( ID INT,NAME NVARCHAR(100),TL_NUM INT,TL_NAME
NVARCHAR(100),MANAGER_NUM INT)
INSERT INTO TAB1
VALUES
(1, 'F-23', 2, 'T-2', 1)
,(2, 'B-23', 3, 'T-3', 2)
,(3, 'F-24', 2, 'T-2', 1)
,(4, 'F-25', 1, 'T-1', 2)
,(5, 'F-26', 2, 'T-2', 2)
,(6, 'F-27', 1, 'T-1', 2)
SELECT DISTINCT t.TL_NUM ,t.TL_NAME ,t.MANAGER_NUM
FROM TAB1 AS t;
Upvotes: 0
Reputation: 139
Your query looks good and working fine but the sorting is not correct according to the output.i have tested the query and its working fine.
select DISTINCT TL_NUM, TL_NAME ,MANAGER_NUM from #dataTable order by MANAGER_NUM
Upvotes: 1