在3个表中选择

时间:2013-09-28 13:07:16

标签: sql sql-server

我有3张桌子

table 1 "Sale" that saved date of user sale 
table 2 "ProductFactor" that saved factorid and productid in wich factoreid
tabel 3 "Product" that saved productid and product name

我希望在3表中选择此结果:

显示用户factorid + price + saledate +此factorid中的avalibe

的任何产品名称

但是当这样做时,例如在一个有3个productid的factorid中,显示这个:

 date       factoreid    name     price 
2013-09-25    1         x         18261256            
2013-09-25    1         y         2365560.0000
2013-09-25    2         w         5500.0000
2013-09-25    3         z         50000.0000
2013-09-25    1         k         324.0000

我希望展示这个:

date    factoreid    name     price 
2013-09-25    1    x,y,k      sum of 3 product name           
2013-09-25    2     w       5500.0000
2013-09-25    3     z       50000.0000
CREATE PROCEDURE [dbo].[GetUserSaleReport] 
@CurrentUserId uniqueidentifier
AS
BEGIN
SELECT dbo.Sale.SaleDate,dbo.ProductFactor.FactoreId,dbo.Product.ProductName,dbo.Product.Price
 FROM Sale INNER JOIN ProductFactor ON 
 dbo.Sale.FactoreId=dbo.ProductFactor.FactoreId
 INNER JOIN dbo.Product ON dbo.ProductFactor.ProductId=dbo.Product.ProductId 
 WHERE dbo.Sale.UserId = @CurrentUserId AND dbo.Sale.FactoreId=dbo.ProductFactor.FactoreId AND dbo.ProductFactor.ProductId=dbo.Product.ProductId
 ORDER BY dbo.Sale.SaleDate
END

1 个答案:

答案 0 :(得分:2)

这可能是您的查询:

select date, factoreid,GROUP_CONCAT(name) , sum(price)
from tablename 
group by factoreid

参考:http://sqlfiddle.com/#!2/284fd/5