我有两个表dbo.Supplier和dbo.L_ProductSupplier(AS LPST)以及LPST表上的所有产品ID,我想连接来自dbo.Supplier(AS ST)的供应商名称,该名称由SupplierID链接到LPST字段(每个产品可以有多个供应商)
e.g。查询应该采用这个:
LPST.ProductID LPST.SupplierID ST.SupplierName
1 A CompanyA
1 B CompanyB
1 C CompanyC
2 X CompanyX
2 Y CompanyY
2 Z CompanyZ
并输出:
LPST.ProductID SupplierName(s)
1 CompanyA / CompanyB /CompanyC
2 CompanyX / CompanyY / CompanyZ
我尝试过以下代码:
SELECT DISTINCT
LPST.ProductId,
STUFF((SELECT ',' + ST.SupplierName
FROM dbo.Supplier AS ST
WHERE LPST.SupplierId=ST.SupplierId
FOR XML PATH('')),1,1,'') AS SupplierNames
FROM dbo.L_ProductSupplier AS LPST
GROUP BY LPST.ProductId
...但是它给出了错误:列'dbo.L_ProductSupplier.SupplierId'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。关于如何解决这个问题的任何想法?如果我删除“分组依据”,则它会报告LPST上的每一行而不连接。
还有另一种方法吗?我听说游标是一个选项,但我是SQL的新手,并不熟悉它们;在这种情况下,有没有人有游标经验?
答案 0 :(得分:0)
怎么样
DECLARE @Supplier TABLE(
SupplierId INT,
SupplierName VARCHAR(50)
)
INSERT INTO @Supplier SELECT 1, 'A'
INSERT INTO @Supplier SELECT 2, 'B'
DECLARE @L_ProductSupplier TABLE(
ProductId INT,
SupplierId INT
)
INSERT INTO @L_ProductSupplier SELECT 1, 1
INSERT INTO @L_ProductSupplier SELECT 1, 2
;WITH Vals AS (
SELECT LPST.ProductId,
LPST.SupplierId,
ST.SupplierName
FROM @L_ProductSupplier LPST LEFT JOIN
@Supplier ST ON LPST.SupplierId = st.SupplierId
)
SELECT LPST.ProductId,
STUFF(
(
SELECT ',' + ST.SupplierName
FROM Vals AS ST
WHERE LPST.ProductId=ST.ProductId
FOR XML PATH('')
),
1,
1,
''
) AS SupplierNames
FROM Vals AS LPST
GROUP BY LPST.ProductId
答案 1 :(得分:0)
Declare @t table (ProductID int, SupplierID varchar(1),SupplierName varchar(50))
insert into @t
select 1 , 'A' , 'CompanyA' union all
select 1 , 'B' , 'CompanyB' union all
select 1 , 'C' , 'CompanyC' union all
select 2 , 'X' , 'CompanyX' union all
select 2 , 'Y' , 'CompanyY' union all
select 2 , 'Z' , 'CompanyZ'
select distinct b.ProductID,stuff((select '/'+a.SupplierName from @t a where a.ProductID=b.ProductID FOR XML path('')),1,1,'')
from @t b