使用默认值在SQL Server视图中创建新列

时间:2017-07-17 12:13:23

标签: sql-server views unions

我对视图有这个查询:

SELECT count(A), sum(B), average(C)
FROM TableA,
LEFT JOIN TableB ON ...
LEFT JOIN TableC ON ...
WHERE
    (very complicated conditions)

我想添加一个带有默认年份值的新列。表格应该是这样的:

IQueryable<Entity> = dbSet
    .Include(e => e.entityB)
    .Include(e => e.EntityC)
    .Where( <very complicated conditions> );

我们正在加入的每个观点都有不同的年份。请协助

1 个答案:

答案 0 :(得分:2)

好的,根据你的评论,你有一个恒定的价值作为你的一年,所以这将做的伎俩:

SELECT t1.Connected, t1.Region, t1.Homespassed, '2017' as Year FROM connected as t1 
UNION ALL 
SELECT t2.Connected, t2.Region, t2.Homespassed, '2018' as Year FROM connected as t2;

或者如果您希望代码更好一些:

DECLARE @YEAR1 CHAR(4), @YEAR2 CHAR(4);
SET @YEAR1 = '2017';
SET @YEAR2 = '2018';

SELECT t1.Connected, t1.Region, t1.Homespassed, @YEAR1 as Year FROM connected as t1 
UNION ALL 
SELECT t2.Connected, t2.Region, t2.Homespassed, @YEAR2 as Year FROM connected as t2;