我有3张桌子
Customer
Customer |Name
1002 |ABB
2006 |Aberdeen C
.
.
和销售收入表
Customer|Inv. |Product |Sales Amount |Gross Margin
1002 |600 |5 |8000 |125
1002 |601 |20 |0 |-10
1002 |602 |0 |320 |160
2006 |603 |7 |120 |0
.
.
应收帐款表
Customer|Inv. |Product |Balance |Line Amount |Amount
1002 |500 |0 |150 |NULL |150
1002 |600 |5 |8000 |8000 |8000
1002 |601 |20 |0 |0 |0
1002 |602 |0 |0 |160 |160
2006 |603 |7 |120 |120 |0
.
.
我想通过将销售收入和应收帐款表加入以下方式来创建客户视图:
Customer|Name|Inv.|Product|Sales Amount |Gross Margin |Balance |Line Amount
1002 |ABB |500 |0 |NULL |NULL |150 |150
1002 |ABB |600 |5 |8000 |125 |8000 |8000
1002 |ABB |601 |20 |0 |-10 |0 |0
1002 |ABB |602 |0 |320 |160 |160 |160
2006 |ABB |603 |7 |120 |0 |120 |0
.
.
我尝试过
CREATE or alter VIEW [dbo].[custmermasterview] as
SELECT [Customer]
,[Name]
,[Inv]
,[Sales Amount]
,[Gross Margin]
,[Balance]
,isnull([Line Amount],[Amount]) as LineAmount
,[dbo].[SalesRevenue].[product_key]
FROM [PDI].[dbo].[Customer]
LEFT JOIN [dbo].[SalesRevenue] ON
([PDI].[dbo].[Customer].[customer_key] = [dbo].[SalesRevenue].[customer_key] and
LEFT JOIN [dbo].[AccountReceivables] ON
([dbo].[SalesRevenue].[Inv] = [dbo].[AccountReceivables].Inv)
显然,它已与SalesRevenue保持连接,因此不会提取AccountReceivables中的记录。如何获得所需的输出?
这有点很难测试,但是我认为这可以工作
SELECT [Customer]
,[Name]
,[Inv]
,[Sales Amount]
,[Gross Margin]
,[Balance]
,isnull([Line Amount],[Amount]) as LineAmount
,[dbo].[SalesRevenue].[product_key]
FROM [PDI].[dbo].[Customer]
LEFT JOIN [dbo].[SalesRevenue] ON
([PDI].[dbo].[Customer].[customer_key] = [dbo].[SalesRevenue].[customer_key]
LEFT JOIN [dbo].[AccountReceivables] ar ON
([dbo].[SalesRevenue].[Inv] = [dbo].[AccountReceivables].Inv)
OR
([PDI].[dbo].[Customer].[customer_key] = [dbo].[AccountReceivables].[customer]
AND NOT EXISTS(SELECT NULL FROM [dbo].[SalesRevenue] sr WHERE sr.[Inv] = ar.[Inv] and
sr.[customer] = ar.[customer] ) )
我在表中添加了一些别名,以便于加入。此外,您的查询使用customer_key进行联接,但是您的表显示为customer?
您可以添加一个子查询,该子查询从两个表中获取所有发票并加入该子查询:
SELECT [Customer]
,[Name]
,[Inv]
,[Sales Amount]
,[Gross Margin]
,[Balance]
,isnull([Line Amount],[Amount]) as LineAmount
,[dbo].[SalesRevenue].[product_key]
FROM [PDI].[dbo].[Customer]
JOIN ( SELECT DISTINCT [customer_key] , inv, product
FROM [dbo].[AccountReceivables]
UNION
SELECT DISTINCT [customer_key] , inv, product
FROM [dbo].[SalesRevenue]
) all
LEFT JOIN [dbo].[SalesRevenue] ON
[dbo].[SalesRevenue].[customer_key] = all.[customer_key]
and [SalesRevenue].inv = all.inv
and [SalesRevenue].product = all.product
LEFT JOIN [dbo].[AccountReceivables] ON
all.[Inv] = [dbo].[AccountReceivables].Inv
and [AccountReceivables].inv = all.inv
and [AccountReceivables].product = all.product