我有两个表“表A”和“表B”
表A是与其他表连接的结果。表B是一个单独的表,表A中有1个字段。
表A:
Year Name Value
2011 A Item1
2010 B 1
2011 C Item2
表B:
id Value
1 Item1
2 Item2
3 Item3
4 Item4
我希望结果如下:
Year Name Value
2011 A Item1
2010 B NULL
2011 C Item2
我的努力是:
SELECT d.Portfolio,
d.Name,
d.AccountName,
d.CashGAAP,
d.OriginalDate,
d.Amount,
d.AccountNumber,
d.AttributeSetName,
d.TheDate,
d.Year,
d.Value
FROM (SELECT Portfolio.LegalEntityName AS Portfolio,
Forecast.Name,
CoA.AccountName,
Forecast_Data.CashGAAP,
CONVERT(DATE, Forecast_Data.TheDate) AS OriginalDate,
SUM(Forecast_Data.Amount) AS Amount,
CoA.AccountNumber ,
Attribute_Set.AttributeSetName,
'' + CONVERT(VARCHAR, YEAR(Forecast_Data.TheDate)) + '-'
+ CONVERT(VARCHAR, MONTH(Forecast_Data.TheDate)) + '-01' AS TheDate,
YEAR(Forecast_Data.TheDate) AS Year,
Forecast_Attribute.Value
FROM Portfolio
INNER JOIN Forecast ON Portfolio.PortfolioID = Forecast.PortfolioID
INNER JOIN Forecast_Account
ON Forecast.ForecastID = Forecast_Account.ForecastID
INNER JOIN Forecast_Data
ON Forecast_Account.ForecastAccountID =
Forecast_Data.ForecastAccountID
INNER JOIN CoA ON CoA.AccountNumber = Forecast_Account.AccountNumber
INNER JOIN Attribute_Set
ON CoA.AttributeSetID = Attribute_Set.AttributeSetID
INNER JOIN Forecast_Attribute
ON Forecast_Account.ForecastAccountID =
Forecast_Attribute.ForecastAccountID
WHERE (Forecast.ForecastID = 5)
OR (Forecast.ForecastID = 6)
GROUP BY Portfolio.LegalEntityName,
Forecast.Name,
CoA.AccountName,
Forecast_Data.CashGAAP,
Forecast_Data.TheDate,
CoA.AccountNumber,
Attribute_Set.AttributeSetName,
Forecast_Attribute.Value)
AS d
LEFT OUTER JOIN Vendor ON d.Value = Vendor.VendorName
我重命名了问题中解释的示例表:
Table A = d
Table B = Vendor
答案 0 :(得分:7)
你应该将JOIN B左转到A并在SELECT列表中显示B.Value
而不是A.Value
:
SELECT Year, Name, B.Value
FROM A
LEFT JOIN B on A.Value=B.Value
答案 1 :(得分:1)
INNER JOIN
关键字选择两个表中的所有行,只要两个表中的列匹配
您需要申请LEFT JOIN
SELECT column_name(s)
FROM TableA
LEFT OUTER JOIN TableB
ON tableA.Value=tableB.Value;
LEFT JOIN
关键字返回左表(tableA)中的所有行,右表(tableB)中的匹配行。当没有匹配时,结果是NULL
在右侧。
答案 2 :(得分:1)
select
A.Year, A.Name, B.Value
from
A left join B on A.Value= B.value;