Tsql T-SQL三重自连接
嘿,伙计们,我对下表有个问题:Tsql T-SQL三重自连接,tsql,Tsql,嘿,伙计们,我对下表有个问题: CREATE TABLE [dbo].[CA]( [Id] [int] IDENTITY(1,1) NOT NULL, [Type] [char](1), [Percent] [numeric](19, 5) NULL, [Crop] [int] NULL, [Currency] [int] NULL, [Ammount] [decimal](19, 5) [ProductionSite] [int] NOT NULL ) 此表描述了ProductionSit
CREATE TABLE [dbo].[CA](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Type] [char](1),
[Percent] [numeric](19, 5) NULL,
[Crop] [int] NULL,
[Currency] [int] NULL,
[Ammount] [decimal](19, 5)
[ProductionSite] [int] NOT NULL
)
此表描述了ProductionSite如何向其供应商付款。它可能是与作物,货币金额或一些其他金额的百分比没有列在这里
“类型”列是一个鉴别器,指示付款类型。
问题是,你可以同时用三种选择付款,两种选择,或者一种选择。因此,对于给定的ProductionSite,表中最多可以有三行(此设计无法更改)
我需要创建一个视图(不允许使用SP/Triggers),每个ProductionSite只显示一行
我不确定我是否遗漏了什么,但我在这件事上遇到了很多麻烦:(
差点忘了,这还有一个额外的问题。视图的列顺序必须始终相同。我是说,因为查询计划并不总是确定性的(如果我是正确的话),所以三重自关联可能会给出不同的结果(按列/行顺序,而不是数据)。我要说的是
SELECT * FROM A LEFT JOIN A AS B LEFT JOIN A AS C
可以返回以下项的子集:
columns(a) + columns(b) + columns(c)
columns(b) + columns(a) + columns(c)
etc..
任何建议/答案都将不胜感激:)首先获取生产站点的不同列表,然后左键加入表格中以获取类型 像这样的
DECLARE @CA TABLE (
[Id] [int] IDENTITY(1,1) NOT NULL,
[Type] [char](1),
[Percent] [numeric](19, 5) NULL,
[Crop] [int] NULL,
[Currency] [int] NULL,
[Ammount] [decimal](19, 5),
[ProductionSite] [int] NOT NULL
)
SELECT *
FROm (
SELECT DISTINCT
[ProductionSite]
FROM @CA
) DistinctSites LEFT JOIN
@CA cType1 ON DistinctSites.ProductionSite = cType1.ProductionSite AND cType1.Type = 'Type1' LEFT JOIN
@CA cType2 ON DistinctSites.ProductionSite = cType2.ProductionSite AND cType1.Type = 'Type2' LEFT JOIN
@CA cType3 ON DistinctSites.ProductionSite = cType3.ProductionSite AND cType1.Type = 'Type3'
解释:完全联接提供了一种方便的方法,可以将所有行(对于给定Id+付款类型)带入同一结果行。困难在于确保只显示一次Id(我也假设是ProductionSite名称),而不管它来自何处。
这样做的一种方法(参见Astander的解决方案)是首先获取一个ID+ProductionSite值的不同列表,并使用它来驱动查询。
这个解决方案是另一种选择,使用COALESCE基本上可以找到第一个非空Id。我们也可以在ProductionSite中使用COALESCE,我想我应该使用Id为空的情况,以便在语义上更加正确。试试这个
Select c.ProductionSite,
Coalesce(c.type, m.type, p.type) type,
c.Crop, m.Currency, p.Percent,
Coalesce(c.type, m.type, p.type) type,
Coalesce(c.Amount, m.Amount, p.Amount) Amount
From CA c -- for crops
Full Join CA m -- for money
On m.ProductionSite = c.ProductionSite
And c.type = 'c'
And m.type = 'm'
Full Join CA p -- for percentage
On p.ProductionSite = c.ProductionSite
And c.type = 'c'
And p.type = 'p'
Thx的详细解释非常多,非常有帮助。我用的是阿斯坦德的答案,因为它看起来更简单:),但正如你所指出的,你的答案也是正确的。公平的说,我总是发现阿斯坦德对SQL问题的回答是“关于钱”。不错的选择!
Select c.ProductionSite,
Coalesce(c.type, m.type, p.type) type,
c.Crop, m.Currency, p.Percent,
Coalesce(c.type, m.type, p.type) type,
Coalesce(c.Amount, m.Amount, p.Amount) Amount
From CA c -- for crops
Full Join CA m -- for money
On m.ProductionSite = c.ProductionSite
And c.type = 'c'
And m.type = 'm'
Full Join CA p -- for percentage
On p.ProductionSite = c.ProductionSite
And c.type = 'c'
And p.type = 'p'