SQL Server查询选择循环列

时间:2018-09-16 06:37:36

标签: sql sql-server

查询有问题。

我有2张桌子,桌子人和桌子收入

我需要这样查询:

ID | Name | Income A | Income B | Income C | .... | ...

ID | Name = from table person
Income A | Income B | Income C = loop from table income

表收入中有收入名称和收入值

Name     | Value
---------+-------
Income A | 100
Income B | 200
Income C | 300

我有第三个表,其中的表保存了身份证人和身份证收入。因此,如果一个人有3个收入,而另一个人有2个收入,则该人有2个收入的结果是,收入填入0

示例

ID | Name   | income A | Income B | income C
---+--------+----------+----------+---------
1  | andre  |  100     |  200     |  300
2  | robert |  100     |  200     |    0

希望你们明白我的意思

1 个答案:

答案 0 :(得分:0)

DECLARE @pivot varchar(60);
DECLARE @sql varchar(6000);
SET @pivot=(SELECT Stuff(
  (SELECT N', [' + T.Name+']' FROM (SELECT DISTINCT Name FROM income) T FOR XML PATH(''),TYPE)
  .value('text()[1]','nvarchar(max)'),1,2,N''));

--  PRINT @pivot;
SET @sql='select * from income pivot (avg(Value) 
          for Name in ('+@pivot+')) as incomes';           


EXECUTE(@sql);

then join with other table and convert join null with 0