尝试使用WITH创建View时出现问题

时间:2015-12-23 15:44:57

标签: sql sql-server

我正在尝试创建以下视图,查询运行查找,直到我尝试创建一个视图,然后我收到一条错误,指出:创建视图或函数失败,因为没有为列1指定列名,研究I已经找到并没有真正帮助,因为它通常是一个简单的查询错误,但我的目前运行正常。任何见解?

CREATE VIEW dbo.prov_prod_rv AS

WITH rep_prods AS (SELECT t.amount, t.provider_id, t.clinic, p.period_start, t.impacts, 
p.period_end, p.period_id, p.fiscal_year, p.date_man
FROM dbo.transactions AS t 
CROSS JOIN dbo.period AS p
WHERE (t.date_entered BETWEEN p.period_start AND p.period_end))

SELECT SUM(r.amount), r.provider_id, d.first_name, d.last_name, d.position_id, d.clinic, r.period_id, r.fiscal_year, r.date_man
FROM rep_prods AS r INNER JOIN
dbo.provider AS d ON r.provider_id = d.provider_id AND r.clinic = d.clinic
WHERE (r.impacts = 'P') AND (r.amount <> 0)
GROUP BY r.provider_id, d.first_name, d.last_name, d.position_id, d.clinic, r.period_id, r.fiscal_year, r.date_man

2 个答案:

答案 0 :(得分:5)

问题在于你的最终SELECT

SELECT   SUM(r.amount), 
         r.provider_id, 
         d.first_name, 
         d.last_name, 
         d.position_id, 
         d.clinic, 
         r.period_id, 
         r.fiscal_year, 
         r.date_man

您需要为SUM(r.amount)列指定一个列名:

SELECT   SUM(r.amount) As TotalAmount, 
         r.provider_id, 
         d.first_name, 
         d.last_name, 
         d.position_id, 
         d.clinic, 
         r.period_id, 
         r.fiscal_year, 
         r.date_man

答案 1 :(得分:2)

第1列是SUM(r.amount)。它没有名称(或别名)。只是将其作为查询运行不是问题,因为SSMS不需要列名,但在视图中视图必须具有列名。给它一个别名,例如SUM(r.amount) AS TotalAmount