我正在使用两个表在SQL Server(SSMS)中工作:
prop_ppl:
id_numb id_pers cdate val 1 4 NULL NULL 2 2 2018-12-12 250 3 1 2018-12-01 250 4 3 2018-12-11 500 5 6 2018-01-01 500 6 5 2018-12-12 480
ppl:
id_perc name 1 John 2 Derek 3 Mia 4 Chris 5 Ann 6 Dave
然后我需要得到这样的表:
name id_numb value
对于这些表,应在必要时查找日期为2018/12/12的ppl的所有值:
Derek Ann 2 250 0 6 0 NULL
代码:
CREATE TABLE ppl( id_perc smallint PRIMARY KEY, name varchar(50) NOT NULL ) CREATE TABLE prop_ppl( id_numb int IDENTITY(1,1) PRIMARY KEY, id_perc smallint NOT NULL, cdate smalldatetime, val int ) INSERT INTO dbo.ppl (id_perc, name) VALUES (1, 'John'), (2, 'Derek'), (3, 'Mia'), (4, 'Chris'), (5, 'Ann'), (6, 'Dave') INSERT INTO dbo.prop_ppl (id_perc, cdate, val) VALUES (4, NULL,NULL), (2,'20181212', 250), (1, '20181201', 250), (3, '20181211',500), (6,'20180101', 500), (5, '20181212', 480)
然后我尝试使用:
SELECT * FROM ( SELECT name,id_numb,val FROM prop_ppl JOIN ppl ON prop_ppl.id_perc = ppl.id_perc WHERE cdate='20181212' ) PIVOT( SUM(val) FOR [name] in ('Derek','Ann') )
但出现错误“ 关键字“ PIVOT”附近的语法不正确。 ”
也许,也可以不使用PIVOT。。另外,我想了解如何将此脚本应用于任意参数(而不仅仅是Derek和Ann)。
使用CTE很容易处理:
With CTE as ( SELECT name, id_numb, val FROM prop_ppl JOIN ppl ON prop_ppl.id_perc = ppl.id_perc WHERE cdate='20181212') Select * from CTE PIVOT(SUM(val) FOR [name] in ([Derek],[Ann])) as Col