查询有效,但仅给出1985年的值。如何添加无限年数(1985-2014)
use baseball;
SELECT CAST(tf.franchname AS CHAR(20)), s.yearID, s.lgid, AVG(s.salary)
FROM salaries s, teams t, teamsfranchises tf
WHERE s.teamID = t.teamID AND
t.franchID = tf.franchID AND
s.yearID = 1985 AND
(s.lgid='AL' OR s.lgid='NL') GROUP BY tf.franchname, s.yearID, s.lgid order BY
s.yearID;
答案 0 :(得分:3)
您可以使用BETWEEN。
你的where子句应该是
(s.yearID BETWEEN 1985 AND 2014) and
或者,您可以使用<
和>
运算符:
(s.yearID >= 1984 and <= 2014)
如果出于任何原因,您没有连续的年份(您只需要5年)。 IN
也可以是一个选项:
s.yearID IN (1984, 1991, 1996, 2001, 2006)
答案 1 :(得分:1)
您的查询在and s.yearID = 1985
年内有条件过滤,您可能需要使用关键字BETWEEN
进行更改,或根据需要将其删除。
答案 2 :(得分:0)
select cast(tf.franchname as char(20)), s.yearID, s.lgid, avg(s.salary)
from salaries s, teams t, teamsfranchises tf
where s.teamID = t.teamID and
t.franchID = tf.franchID and
(s.yearID between 1985 and 2014 )and
(s.lgid='AL' OR s.lgid='NL')
group by tf.franchname, s.yearID, s.lgid
order by s.yearID;
答案 3 :(得分:0)
这是另一种观点,当没有数据时仍然希望得到零计数的年份。只需查看此link
即可在这里你可以创建一个临时表,返回你的年份列表,即1985年到2015年,然后加入左外连接,看看魔术。
我只是得到你的查询,你也可以用接受的答案查询替换。
Declare @Startyear int = 1985
--1st approach to get continues year
;with yearlist as
(
select 1985 as year
union all
select yl.year + 1 as year
from yearlist yl
where yl.year + 1 <= YEAR(GetDate())
)
select year from yearlist order by year desc;
--2nd approach to get continues year
;WITH n(n) AS
(
SELECT 0
UNION ALL
SELECT n+1 FROM n WHERE n < (year(getdate()) -@Startyear)
)
SELECT year(DATEADD( YY, -n, GetDate()))
FROM n ORDER BY n
--take anyone approach and then join with your query
;with yearlist as
(
select 1985 as year
union all
select yl.year + 1 as year
from yearlist yl
where yl.year + 1 <= YEAR(GetDate())
)
select year from yearlist
left join
(
SELECT CAST(tf.franchname AS CHAR(20)), s.yearID, s.lgid, AVG(s.salary)
FROM salaries s, teams t, teamsfranchises tf
WHERE s.teamID = t.teamID AND
t.franchID = tf.franchID AND
s.yearID = 1985 AND
(s.lgid='AL' OR s.lgid='NL') GROUP BY tf.franchname, s.yearID, s.lgid order BY
s.yearID
) yourtable on yourtable.yearID = yearlist.year
order by year desc;