即使数据不存在,也要选择相同的行数

时间:2014-11-14 00:01:37

标签: sql select

我想编写一个查询来始终选择相同数量的行,即使数据不存在也是如此。如果数据不存在,我仍然想在其位置选择一些内容。

例如,如果我想在过去5年中选择我的银行帐户中的金额,但我只有过去3年的数据,我是否仍然可以选择5行,只需要0' s两年失踪?

| Year | Balance |
| 2014 | $5      |
| 2013 | $10     |
| 2012 | $31     |
| 2011 | $0      | << Doesn't exist
| 2010 | $0      | << Doesn't exist

这可能吗?谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

使用mssql,这将有效。其他DB还有其他类似的功能。 SELECT TOP 5 year, ISNULL(balance,0) FROM yourtable

答案 1 :(得分:0)

解决这个问题的关键是使用外连接。很容易将您的实际数据表视为“主要”表格,但您真正想要的是所有可能年份的表格。我没有多年的表,所以我在飞行中做了一个:

select 2010 as Year union select 2011 as Year union select 2012 as Year union select 2013 as Year union select 2014 as Year

这给了我一份我关心的所有年份的清单。

然后我使用外部联接将其与真实数据连接到我的表。外连接只返回 NULL 值,表示不存在的东西。但我不想 NULL ,我想要零,所以如果它们为null,我使用isnull函数使它们为零。然后我最终得到了这个:

select YearList.Year, isnull(Bals.Balance, 0) as theBalance from (select 2010 as Year union select 2011 as Year union select 2012 as Year union select 2013 as Year union select 2014 as Year) as YearList left join (select Year, Balance from Balances) as Bals on YearList.Year = Bals.Year