我有一个以前在MS Access中工作得很漂亮的查询,我试图将其作为视图引入SQL Server。问题是两个字段从其他视图中获取其值。这些观点完美无缺。我正试图从这两个领域获得他们的百分比评级。查询类型如下所示:
SELECT dbo.v_IPQueryTotal,
GEOLOC.City,
GEOLOC.State,
dbo.v_IPQueryTotal AS [Total],
dbo.v_IPHits AS [Confirmed],
[Confirmed] / [Total] * 100 AS Percentage
FROM GEOLOC,
v_IPQueryTotal;
答案 0 :(得分:0)
使用SQL Server在同一语句中无法引用内联列别名。您需要直接引用列,如下所示:
SELECT
dbo.v_IPQueryTotal,
GEOLOC.City,
GEOLOC.State,
dbo.v_IPQueryTotal.AllHits AS [Total],
dbo.v_IPHits.IPHitCount AS [Confirmed],
dbo.v_IPHits.IPHitCount / dbo.v_IPQueryTotal.AllHits * 100 AS Percentage
FROM
GEOLOC, v_IPQueryTotal
另一个解决方案是使用内部派生表并在外部查询中引用它们的列:
SELECT
tmp.*,
tmp.Confirmed / tmp.Total * 100 AS Percentage
FROM
(
SELECT
dbo.v_IPQueryTotal,
GEOLOC.City,
GEOLOC.State,
dbo.v_IPQueryTotal.AllHits AS [Total],
dbo.v_IPHits.IPHitCount AS [Confirmed]
FROM
GEOLOC, v_IPQueryTotal
) tmp
实际上没有定义连接条件因此导致笛卡尔积可能不符合您的预期。