我在ms-sql 2008中有2个表
Data_CardCustomer
它有>> CustomerId
,Code
,Name
,...等字段
Data_ActionPriceList
它有>> CustomerId
,StockId
,Price1
,Price2
,Price3
字段
我想汇总所有客户记录的所有价格
如果customerId
在DataActionPriceList
表中没有价格,则它将返回零。
Code,Price1,Price2,Price3
当前查询
SELECT Code,
Isnull((select Price1 from Data_ActionPriceList where Data_ActionPriceList.CustomerId=Data_CardCustomer.CustomerId and StockId=10005 ),0) As price1,
Isnull((select Price2 from Data_ActionPriceList where Data_ActionPriceList.CustomerId=Data_CardCustomer.CustomerId and StockId=10005 ),0) As price2,
Isnull((select Price3 from Data_ActionPriceList where Data_ActionPriceList.CustomerId=Data_CardCustomer.CustomerId and StockId=10005 ),0) As price3
FROM Data_CardCustomer
有更简单的方法吗?
答案 0 :(得分:1)
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
答案 1 :(得分:1)
在你的问题标题中,你的想法正确。
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
AND dapl.StockId = 10005
请注意:您也可以使用JOIN
代替LEFT JOIN
,具体取决于您的预期结果。使用JOIN
,您只会获得两个表中包含相应条目的行,而您将使用Data_CardCustomer
从LEFT JOIN
检索所有行。