如何从三个表中选择不同的数据?

时间:2015-08-21 06:06:01

标签: sql-server join

如何编写SQL语句以从三个表中选择不同的数据? 有三个表

1)

Registration 

      id  name contact

  123 abc  123456789

2)bookingReg

   PkBkID FkRegID ac_no 

   1       123     QT123 

3)产品

   PkPro FkBkID pro_name Qty price 

    1     1     abc      2   150

    2     1     def      1   400

    3     1     ghi      5   500

    4     1     abc      2   150

SELECT * FROM Registration as a

JOIN bookingReg as b ON (b.FkRegID = '123')

JOIN products as c ON (c.FkBkID = b.PkBkID ) 

我想要不同的pro_name

Out put is

ac_no  qty price

QT123  8   1050

HOw?

2 个答案:

答案 0 :(得分:0)

根据我的假设回答

SELECT    pro_name, 
          ac_no, 
          SUM(qty) Sumqty, 
          SUM(price) SumPrice
FROM Registration a    
JOIN bookingReg b 
    ON b.FkRegID = a.id    
JOIN products c 
    ON c.FkBkID = b.PkBkID  
GROUP BY pro_name, ac_no

编辑如果您不想在结果中看到此字段,请从ac_noSELECT移除GROUP BY

答案 1 :(得分:0)

请试试这个

SELECT A.ac_no, SUM(A.Qty) Qty, SUM(A.Price) Price
FROM 
(
SELECT DISTINCT B.ac_no, P.Qty, P.Price
FROM Registration R
INNER JOIN bookingReg B ON B.FkRegID  = R.id
INNER JOIN products P ON P.FkBkID = B.PkBkID
) A
GROUP BY A.ac_no

Result-ScreenShot