获取一个表的所有行,并匹配SQL

时间:2018-06-06 18:08:47

标签: sql ms-access

所以我所拥有的是一个数据库,其中记录与IDYEAR相关联。每个YEAR每个ID只会有一条记录,但每个ID并不一定存在于给定的YEAR中。所以,我想要做的就是从2018年YEAR的表格中获取每张记录的清单,并从前三年获得一定的价值。我的问题是,如果2018年的记录在2017年没有存在,我根本就不会得到它。我想用0或其他东西填充NULL字段,但仍然保留ID

到目前为止(显然不起作用)是:

SELECT a.ID, b.VAL, c.VAL, d.VAL
FROM table as a, table as b, table as c, table as d
WHERE a.YEAR = 2018 AND b.YEAR = 2017 AND c.YEAR = 2016 AND d.YEAR = 2015 AND a.ID = b.ID AND b.ID = c.ID AND c.ID = d.ID;

我尝试过如下连接:

SELECT a.ID, b.VAL FROM table as a LEFT JOIN table as b on a.ID = b.ID WHERE...

但仍然显示同样的问题。我还应该提到我在MS ACCESS中这样做。

2 个答案:

答案 0 :(得分:0)

希望我理解您所描述的数据结构。下面的变量表是我的解释。如果这是正确的,那么它下面的代码应该为您提供您正在寻找的内容。

关键区别在于' AND'在' ON'条款vs在' WHERE'。如果您将标准放在' WHERE'那么你实际上通过断言在连接完成后标准必须为真,将你的LEFT OUTER JOIN变成INNER JOIN。而在' ON'你告诉SQL它必须是真的才能进行连接。

declare @tbl table ([year] int, [id] int, [someval] varchar(50))
insert into @tbl values (2018, 1, 'one')
insert into @tbl values (2018, 2, 'two')
insert into @tbl values (2017, 1, 'three')
insert into @tbl values (2016, 1, 'four')
insert into @tbl values (2015, 1, 'five')
insert into @tbl values (2015, 2, 'six')
insert into @tbl values (2015, 3, 'seven')

;with t2018 as(select * from @tbl where [year]=2018)
,t2017 as(select * from @tbl where [year]=2017)
,t2016 as(select * from @tbl where [year]=2016)
,t2015 as(select * from @tbl where [year]=2015)
select isnull(t2018.id,isnull(t2017.id,isnull(t2016.id,t2015.id))) as id,
     t2018.someval as [2018SomeVal],
     t2017.someval as [2017SomeVal], 
     t2016.someval as [2016SomeVal], 
     t2015.someval as [2015SomeVal]
from t2018
    full outer join t2017 on t2017.id = t2018.id
    full outer join t2016 on t2016.id = t2018.id
    full outer join t2015 on t2015.id = t2018.id

答案 1 :(得分:0)

我只会使用条件聚合:

SELECT a.ID,
       SUM(IIF(a.YEAR = 2018, a.VAL, 0)) as val_2018,
       SUM(IIF(a.YEAR = 2017, a.VAL, 0)) as val_2017,
       SUM(IIF(a.YEAR = 2016, a.VAL, 0)) as val_2016,
       SUM(IIF(a.YEAR = 2015, a.VAL, 0)) as val_2015
FROM table as a
WHERE a.YEAR IN (2015, 2016, 2017, 2018)
GROUP BY a.id;

如果您只想要存在2018的行,请包含:

HAVING MAX(a.YEAR) = 2018