对标题表示歉意,但我试图做的事情甚至超出我的水平,甚至让我解释一下。
假设我有一个表,其中包含变量人员,食品和数量:
Person food Amount Mike Butter 3 Mike Milk 4 Mike Chicken 2 Tim Milk 4 John Chicken 2
通过在查询中将表与其自身连接起来,我成功地列出了一个列表,其中食物是新变量的基础,而值是数量。上表将变为:
Person Butter Milk Chicken Mike 3 4 2
该代码大约是:
Select a.person, b.amount as Butter, c.amount as Milk, d.amount as Chicken from PersonFoodAmount a inner join PersonFoodAmount b on a.person = b.person inner join PersonFoodAmount c on a.person=c.person where b.food='Butter' and c.food='Milk' and d.food='Chicken'
现在,这给了我迈克,因为他已选中所有复选框。但是我还需要部分匹配:
Person Butter Milk Chicken Mike 3 4 2 Tim NULL 4 NULL John NULL Null 2
我尝试了所有类型的连接,包括完全外部连接,但我仍然只能得到配备完整冰箱的人员。
有什么建议?
您可以使用Pivot进行此操作。
DECLARE @PersonStuff TABLE (Person varchar(10), Food varchar(10), Amount INT) INSERT INTO @PersonStuff VALUES ('Mike','Butter', 3), ('Mike','Milk', 4), ('Mike','Chicken', 2), ('Tim','Milk', 4), ('John','Chicken', 2) SELECT * FROM ( SELECT * FROM @PersonStuff ) AS SourceTable PIVOT ( AVG(Amount) FOR Food IN ( [Butter],[Milk],[Chicken] ) ) AS PivotTable
结果:
Person Butter Milk Chicken John NULL NULL 2 Mike 3 4 2 Tim NULL 4 NULL