所以我已加入数据透视表,我想加入另一个:
Customers Name Surname
1 Adam Sandler
2 John Smith
原始表格是:
ID Food
1 Chicken
2 Pork
和
Customers Food Cost
1 1 45
1 2 12
2 2 12
如何让它看起来像这样:
Customers Chicken Pork Name Surname
1 45 12 Adam Sandler
2 NULL 12 John Smith
答案 0 :(得分:0)
试试这个:
declare @tab1 table(id int,food char(50))
declare @tab2 table(customers int, food int, cost int)
declare @tab3 table(customers int,name char(100),surname char(100))
insert into @tab1 values ('1','Chicken'),('2','Pork')
insert into @tab2 values (1,1,45),(1,2,12),(2,2,12)
insert into @tab3 values (1,'Adam','Sandler'),(2,'John','Smith')
select * from
(select t2.customers,t3.name,t3.surname,t2.cost,t1.food from @tab2 t2,@tab3 t3, @tab1 t1 where t2.customers=t3.customers and t1.id=t2.food) a
pivot ( max(a.cost) for a.food in ([Chicken],[Pork]))p
答案 1 :(得分:0)
或者你可以尝试这个。
样本表:
---Table @Customer
ID NAME SURNAME
----- -------- -------
1 Adam Sandler
2 John Smith
--- Table @Food
ID NAME
----------- --------
1 Chicken
2 Pork
--- Table @FoodCost
ID CustomerID FoodId Cost
----------- ----------- ----------- --------
1 1 1 45.00
2 1 2 12.00
3 2 2 12.00
您可以在转动之前先加入Customer表。
----I used ***Stuff function,
----to determine content of table @food- column name dynamically.
DECLARE @DynamicColumn NVARCHAR(354) = STUFF(( SELECT DISTINCT
', '
+ QUOTENAME(f.NAME)
FROM @FoodCost FC
LEFT JOIN @Food F ON F.ID = fc.FoodId
FOR
XML PATH('')
), 1, 2, '')
IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL
BEGIN
DROP TABLE #tmpTable
END
CREATE TABLE #tmpTable
(
Customer INT ,
Food NVARCHAR(50) ,
[Name] NVARCHAR(50) ,
Surname NVARCHAR(50) ,
Cost NUMERIC(22, 2)
)
INSERT INTO #tmpTable
( Customer ,
Food ,
Name ,
Surname ,
Cost
)
SELECT Fc.CustomerID ,
f.NAME [Food] ,
c.NAME ,
SURNAME ,
fc.Cost
FROM @FoodCost FC
LEFT JOIN @Customer C ON C.ID = FC.CustomerID --- <---Joining Customer Table
LEFT JOIN @Food F ON F.ID = fc.FoodId
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = N'
SELECT
Customer,
' + @DynamicColumn + ',
Name,
Surname
FROM (
SELECT Customer,Food,Name, Surname,Cost FROM #tmpTable
)P pivot ( SUM(p.Cost) for p.Food in (' + @DynamicColumn + '))PVT'
EXEC (@SQL)
结果:
Customer Chicken Pork Name Surname
-------- ------- ------- ------ -------
1 45.00 12.00 Adam Sandler
2 NULL 12.00 John Smith
(2 row(s) affected)
*** Stuff function