如何在SQL Server中获得预期的输出

时间:2018-06-22 15:36:57

标签: sql-server sql-server-2008

我对SQL Server有疑问:如何根据下表数据获取所需的输出?

表格: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')

基于上述数据,我希望输出如下:

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

我这样尝试过:

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

此查询未返回预期结果。

请告诉我如何编写查询以在SQL Server中完成此任务。

1 个答案:

答案 0 :(得分:1)

这里有一段逻辑:“如果[当前记录]。[ParentSupplierId]为空且[先前记录]。[ParentSupplierId]为空,那么[当前记录]。[ParentSupplierId] = [先前记录]。[ SupplierId]”。

但是,除非您使用ORDER BY子句,否则不会按插入的顺序返回SQL记录,并且不指定返回的行顺序。最简单的方法是将ID字段添加到表中,并将其用于[Previous Record],如下所示:

CREATE TABLE [dbo].[parent]
(
    [parentId] int IDENTITY(1,1),
    [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')

然后使用您的基本逻辑找到正确的父母,请尝试:

SELECT DISTINCT  
    ISNULL( a.[parentsupplierid],b.[supplierid]) [parentsupplierid],
    --A.[parentsupplierid]
    A.[supplierid],
    A.[suppliername],
    B.[suppliername] AS [PARENTsuppliername]
FROM   
    [whatsup].[dbo].[parent] A  --- Table for base records
LEFT JOIN [whatsup].[dbo].[parent] M  -- Join for missing parent
    ON M.[parentId] = (A.[parentId] - 1)
    AND M.[parentsupplierid] IS NULL
    AND A.[parentsupplierid] IS NULL
INNER JOIN [whatsup].[dbo].[parent] B
    ON ISNULL(A.parentsupplierid, M.supplierId) = B.supplierid