我有一个包含三列的表:countrycode
,year
和values
。 Year
由若干年(2000年,2001年和2002年)组成。我需要选择特定年份的数据并将其显示为新列。
SELECT g.countrycode, g.values AS '2000'
FROM `gainfinal` g
WHERE `year` = '2000'
我使用上面的查询返回了两列年份和2000年,列'2000'包含2000年的值。现在我需要从其他年份2001和2002中选择数据并以类似的方式显示它。如何再创建两个列两年。
答案 0 :(得分:0)
您将使用条件聚合。将聚合函数与CASE语句结合使用。
以下是总结2000年到2003年之间年份值的示例。
SELECT g.countrycode,
sum(case when `year` = '2000' then g.values else 0 end) AS "2000",
sum(case when `year` = '2001' then g.values else 0 end) AS "2001",
sum(case when `year` = '2002' then g.values else 0 end) AS "2002",
sum(case when `year` = '2003' then g.values else 0 end) AS "2003"
FROM `gainfinal` g
WHERE `year` between '2000' and '2003'
group by g.countrycode
您的示例数据不包含年份为2002或2003的任何行。因此它们应为零。
如果需要2004的数据,则必须将2004添加到WHERE子句中的范围,并将其CASE语句添加到SELECT列表中,如下所示。
然而,2002年和2003年仍将全部为零,因为它们是零。
SELECT g.countrycode,
sum(case when `year` = '2000' then g.values else 0 end) AS "2000",
sum(case when `year` = '2001' then g.values else 0 end) AS "2001",
sum(case when `year` = '2002' then g.values else 0 end) AS "2002",
sum(case when `year` = '2003' then g.values else 0 end) AS "2003",
sum(case when `year` = '2004' then g.values else 0 end) AS "2004"
FROM `gainfinal` g
WHERE `year` between '2000' and '2004'
group by g.countrycode
您必须指定年份范围,并且在每个要输出的年份的选择列表中都有一个案例陈述。没有纯粹的SQL解决方案可以动态确定列。为此,您可能会更好地在Excel中制作数据透视表。以上假设您知道您希望提前显示数据的年份。
因此,如果你想要1995年至2012年,你必须每年都有一份CASE声明,如下所示:
SELECT g.countrycode,
sum(case when `year` = '1995' then g.values else 0 end) AS "1995",
sum(case when `year` = '1996' then g.values else 0 end) AS "1996",
sum(case when `year` = '1997' then g.values else 0 end) AS "1997",
sum(case when `year` = '1998' then g.values else 0 end) AS "1998",
sum(case when `year` = '1999' then g.values else 0 end) AS "1999",
sum(case when `year` = '2000' then g.values else 0 end) AS "2000",
sum(case when `year` = '2001' then g.values else 0 end) AS "2001",
sum(case when `year` = '2002' then g.values else 0 end) AS "2002",
sum(case when `year` = '2003' then g.values else 0 end) AS "2003",
sum(case when `year` = '2005' then g.values else 0 end) AS "2004",
sum(case when `year` = '2006' then g.values else 0 end) AS "2005",
sum(case when `year` = '2007' then g.values else 0 end) AS "2006",
sum(case when `year` = '2008' then g.values else 0 end) AS "2007",
sum(case when `year` = '2009' then g.values else 0 end) AS "2008",
sum(case when `year` = '2010' then g.values else 0 end) AS "2009",
sum(case when `year` = '2011' then g.values else 0 end) AS "2010",
sum(case when `year` = '2012' then g.values else 0 end) AS "2011",
sum(case when `year` = '2012' then g.values else 0 end) AS "2012"
FROM `gainfinal` g
WHERE `year` between '1995' and '2012'
group by g.countrycode