MSSQL左外连接更简单的方法
我在ms sql 2008中有两个表MSSQL左外连接更简单的方法,sql,sql-server,tsql,left-join,Sql,Sql Server,Tsql,Left Join,我在ms sql 2008中有两个表 数据\u卡客户 它有>>客户ID,代码,名称。。。等领域 数据\u操作价格表 它有>>CustomerId,StockId,Price1,Price2,Price3字段 我想汇总所有客户记录的所有价格。 如果customerId在DataActionPriceList表中没有价格,则应返回零 Code,Price1,Price2,Price3 有更简单的方法吗?你的问题标题中有你的想法,这是正确的 SELECT Data_CardCustomer.Code,
数据\u卡客户
它有>>
客户ID
,代码
,名称
。。。等领域
数据\u操作价格表
它有>>
CustomerId
,StockId
,Price1
,Price2
,Price3
字段
我想汇总所有客户记录的所有价格。如果
customerId
在DataActionPriceList
表中没有价格,则应返回零
Code,Price1,Price2,Price3
有更简单的方法吗?你的问题标题中有你的想法,这是正确的
SELECT Data_CardCustomer.Code,
Isnull(Data_ActionPriceList.Price1 ,0) As price1,
Isnull(Data_ActionPriceList.Price2 ,0) As price2,
Isnull(Data_ActionPriceList.Price3 ,0) As price3
FROM Data_CardCustomer
left join Data_ActionPriceList on Data_ActionPriceList.CustomerId=Data_CardCustomer.CustomerId and StockId=10005
SELECT
dcc.Code,
Isnull(dapl.Price1, 0) As price1,
Isnull(dapl.Price2, 0) As price2,
Isnull(dapl.Price3, 0) As price3
FROM
Data_CardCustomer dcc LEFT JOIN Data_ActionPriceList dapl ON dapl.CustomerId = dcc.CustomerId
和dapl.StockId=10005
请注意:您也可以使用
JOIN
而不是LEFT JOIN
,具体取决于您的预期结果。使用JOIN
在两个表中只会得到具有相应条目的行,而在查询中使用LEFT JOIN
从Data\u CardCustomer
检索所有行,如果客户在Data\u ActionPriceList中没有任何记录,则不在结果中显示。因为您在Where上使用dapl.StockId=10005,而不是在“On”上。您是对的,但这取决于OP的期望。问题不完全清楚…问题清楚与否你把条件放在where中打破了左连接。这是没有目的的。我在看,类似的东西。谢谢
SELECT
dcc.Code,
Isnull(dapl.Price1, 0) As price1,
Isnull(dapl.Price2, 0) As price2,
Isnull(dapl.Price3, 0) As price3
FROM
Data_CardCustomer dcc LEFT JOIN Data_ActionPriceList dapl ON dapl.CustomerId = dcc.CustomerId