我确实想创建一个能够将多行选择到列中的选择。如果年份不存在,则显示该年份的 NULL 值
例如下表
CREATE TABLE [dbo].[MPG_TABLE](
[Driver] [char](40) NULL,
[Plate] [char](20) NOT NULL,
[Type] [char](20) NOT NULL,
[Build] [char](6) NULL,
[Miles] [float] NULL,
[Gallon] [float] NULL,
[MPG] [numeric](8, 2) NULL
) ON [PRIMARY]
填表:
insert into MPG_TABLE (Driver, Plate, Type, Build, Miles, Gallon)
values ('JOHN', 'AAAA', '4X4', '2010', 20000, 2100),
('JOHN', 'AAAA', '4X4', '2011', 30000, 2900),
('JOHN', 'AAAA', '4X4', '2012', 25000, 2300),
('JOHN', 'AAAA', '4X4', '2013', 21420, 2130),
('PETER', 'BBBB', 'LUXE', '2011', 22040, 1650),
('PETER', 'BBBB', 'LUXE', '2012', 24000, 1800),
('JACK', 'CCCC', 'LORRY', '2009', 180040, 96005),
('JACK', 'CCCC', 'LORRY', '2010', 220040, 100005),
('JACK', 'CCCC', 'LORRY', '2011', 240000, 100235),
('ADRIAN', 'EEEE', 'LUXE', '2010', 19040, 1450),
('ADRIAN', 'EEEE', 'LUXE', '2011', 30000, 2200),
('ADRIAN', 'DDDD', 'LUXE', '2012', 22040, 1650),
('ADRIAN', 'DDDD', 'LUXE', '2013', 24000, 1800),
('JERRY', 'FFFF', 'LUXE', '2013', 2000, 100)
现在更新最后一列:
update MPG_TABLE
set MPG = (Miles / Gallon)
我有类似的东西,但它没有显示我想要的东西:
select distinct c.Driver, c.Plate, c.Type, a.build, a.Miles, a.gallon,
a.mpg, b.build, b.miles, b.gallon, b.mpg, c.build, c.miles, c.gallon, c.mpg
from MPG_TABLE as a left outer join MPG_TABLE as b
on ISNULL(a.Driver, null) = ISNULL(b.driver, null),
MPG_TABLE as c
where a.Build = '2012'
and b.Build = '2013'
and c.Build = '2011'
结果应如下所示:
2009 2010 2011
Driver Plate Type Miles Gallon MPG Miles Gallon MPG Miles
JOHN AAAA 4X4 NULL NULL NULL 20000 2100 9.52 30000
PETER BBBB LUXE NULL NULL NULL NULL NULL NULL 22040
JACK CCCC LORRY 180040 96005 1.88 220040 100005 2.2 240000
ADRIAN EEEE LUXE NULL NULL NULL 19040 1450 13.13 30000
ADRIAN DDDD LUXE NULL NULL NULL NULL NULL NULL NULL
JERRY FFFF LUXE NULL NULL NULL NULL NULL NULL NULL
如何为此创建选择?