I have a question about SQL Server: how to get required output based on below table data?
Table: parent
CREATE TABLE [dbo].[parent]
(
[parentsupplierid] [int] NULL,
[supplierid] [int] NULL,
[suppliername] [varchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[parent] ([parentsupplierid], [supplierid], [suppliername])
VALUES (123, 321, N'AAA'), (123, 231, N'BBB'),
(NULL, 123, N'ABC'), (456, 654, N'DDD'),
(NULL, 546, N'EEE'), (NULL, 456, N'DEF'),
(789, 987, N'GGG'), (NULL, 879, N'HHH'),
(NULL, 789, N'GHI')
based on above data I want output like below:
parentsupplierid | supplierid | suppliername | PARENTsuppliername
-----------------+------------+--------------+-----------------
123 | 231 | BBB | ABC
123 | 321 | AAA | ABC
456 | 654 | DDD | DEF
456 | 546 | EEE | DEF
789 | 987 | GGG | GHI
789 | 879 | HHH | GHI
I tried like this:
SELECT DISTINCT
ISNULL( a.[parentsupplierid],b.[supplierid]) [parentsupplierid],
--A.[parentsupplierid]
A.[supplierid],
A.[suppliername],
B.[suppliername] AS [PARENTsuppliername]
FROM
[whatsup].[dbo].[parent] A
LEFT JOIN
(SELECT
[parentsupplierid],
[supplierid],
[suppliername]
FROM
[whatsup].[dbo].[parent]
WHERE
[parentsupplierid] IS NULL) B ON A.parentsupplierid = B.supplierid
This query is not returning the expected result.
Please tell me how to write query to achieve this task in SQL Server.
456would be the parent of546. How are they related? Same with789and879...