我有一些桌子。我希望以一种方式加入他们,我只想从内部联接返回行,但我找不到办法做到这一点。我需要帮助。如何使用SQL中的商店prosedure获得类似该表的结果。谢谢!
--------------------------------------------------------------------------------------
| 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');
答案 0 :(得分: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
Dynamic Pivot:
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