2

我有几张桌子。我想以一种我只想从内部连接返回行的方式加入它们,但我找不到这样做的方法。我需要帮助。如何使用 SQL 中的存储程序获得类似该表的结果。谢谢!

--------------------------------------------------------------------------------------
| AltMusteriID | Ad    | Soyad | Gsm1       | Marka | Model | Ozel Alan3 | Ozel Alan4 |
--------------------------------------------------------------------------------------
| 1            | İLKER | Yasin | 5337777158 | OPEL  | CORSA | null       | null       |
| 2            | CEM   | ÇİÇEK | 5666667159 | FİAT  | null  | null       | null       |
| 3            | MEHMET| KURU  | 5222237160 | null  |null   |null        | null       |
--------------------------------------------------------------------------------------


 create table tbl_AltMusteriler
(
  AltMusteriID int,
  Ad nvarchar(50),
  Soyad nvarchar (50),
  Gsm1 nvarchar (50)
);

insert into tbl_AltMusteriler values
(1, 'İLKER', 'YASİN','5337777158'),
(2, 'CEM', 'ÇİÇEK','5666667159'),
(3, 'MEHMET', 'KURU','5222237160'),


create table tbl_OzelAlanlar
(
  OzelAlanID int,
  AltMusteriID int,
  UserOzelAlanID int,
  Degeri nvarchar(50)  
);

insert into tbl_OzelAlanlar values
(1,1,1, 'OPEL'),
(2,1,2, 'CORSA'),
(3,2,1, 'FİAT'),


create table tbl_UserOzelAlanlar
(
  UserOzelAlanID int,
  Alan nvarchar(50)  
);

insert into tbl_UserOzelAlanlar values
(1,'MARKA'),
(2,'MODEL'),
(3,'OZEL ALAN3'),
(4,'OZEL ALAN4');
4

1 回答 1

1

你需要的是PIVOT,试试这个

;with cte as
(
  select a.AltMusteriID, Ad, Soyad, Gsm1, ALAN, Degeri
  from tbl_OzelAlanlar a
  inner join tbl_AltMusteriler b on a.AltMusteriID = b.AltMusteriID
  inner join tbl_UserOzelAlanlar c on a.UserOzelAlanID = c.UserOzelAlanID
)
select * from cte
pivot(max(Degeri) for alan in (MARKA, MODEL, [OZEL ALAN3], [OZEL ALAN4]))p

SQL 演示

动态枢轴:

declare @cols AS nvarchar(MAX);
declare @query AS nvarchar(MAX);

SET @cols = stuff((select distinct ',' + QUOTENAME(alan) 
            from tbl_UserOzelAlanlar
            for XML PATH('')) 
        ,1,1,'')

set @query = '
;with cte as
(
  select a.AltMusteriID, Ad, Soyad, Gsm1, ALAN, Degeri
  from tbl_OzelAlanlar a
  inner join tbl_AltMusteriler b on a.AltMusteriID = b.AltMusteriID
  inner join tbl_UserOzelAlanlar c on a.UserOzelAlanID = c.UserOzelAlanID
)
select AltMusteriID, Ad, Soyad, Gsm1, ' + @cols + '
from cte
pivot(max(Degeri) for alan in ( ' + @cols + '))p'

exec @query
于 2013-03-15T21:43:26.170 回答