我是SQL新手,不知道如何从临时表中总结两列,欢迎任何帮助。
脚本如下:
SELECT
Provider,
StartYear,
CAST(YEAR([EndYear]) AS INT) AS 'EndYear'
INTO
#a
FROM
TABLE1
SELECT
*, SUM(EndYear - StartYear) AS 'Years'
FROM
#a
我收到错误消息:
a.provider在选择列表中无效,因为它未包含 在聚合函数或GROUP BY子句中
样本数据
Provider StartYear EndYear
A1 1940 15/04/2016 00:00
A2 1930 08/06/2016 00:00
A3 1932 04/06/2016 00:00
A2 1932 15/06/2016 00:00
A1 1944 01/07/2016 00:00
答案 0 :(得分:1)
您不需要临时桌子。我想你想要这样的东西:
SELECT t1.*,
(t1.EndYear - t1.StartYear) as Years
FROM table1 t1;
或:
SELECT t1.*,
DATEDIFF(year, t1.StartYear, t1.EndYear) as Years
FROM table1 t1;
修改:如果您确实想要对这些值求和,只需删除t1.*
并添加sum()
:
SELECT SUM(t1.EndYear - t1.StartYear) as Years
FROM table1 t1;
在您的情况下,您应该修复列的名称。称为"年"不应该是约会时间。但是,很容易转换:
SELECT SUM(YEAR(t1.EndYear) - t1.StartYear) as Years
FROM table1 t1;