我回来了另一个问题。我现在一直在修补这个1天半,但仍然没有运气。所以我有下表。
Table1
Field1 Field2 Field3 Field4 Field5
DR1 500 ID1 Active TR1
DR2 250 ID2 Active TR1
DR3 100 ID1 Active TR1
DR4 50 ID3 Active TR1
DR5 50 ID1 Cancelled TR1
DR6 150 ID1 Active TR2
Table2
Field1 Field3
ID1 Chris
ID2 John
ID3 Jane
Table3
Field1 Field2
TR1 Shipped
TR2 Pending
我目前可以达到这个结果。
Name Total
Chris 650 3
John 250 1
Jane 50 1
使用此sql语句
SELECT t2.Field3 as Name , SUM(t1.Field2) as Total
FROM [Table1] t1 INNER JOIN [Table2] t2 ON t1.Field3 = t2.Field1
GROUP BY t2.Field3
但是,我想实现下面显示的结果。
Chris 600 2
John 250 1
Jane 50 1
我想首先检查Table3是否有'Shipped'Field2然后它包含Table1中带有'Active'Field4的所有内容。它不应该包括'已取消'Field4。如果Table3有一个待定的Field2,它也应该不包括它。我很感激任何帮助。谢谢。
答案 0 :(得分:6)
好吧,你只需要加入所有需要在where子句中包含所需字段的表。
并添加where
子句。
SELECT t2.Field3,
SUM(t1.Field2) as CTotal,
count(*) as NbItems
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.Field3 = t2.Field1
--add a join on Table3
INNER JOIN Table3 t3
ON t3.Field1 = t1.Field5
--add your where clause
WHERE t1.Field4 = 'Active'
AND t3.Field2 <> 'Pending'
GROUP BY t2.Field3
--ORDER BY CTotal DESC
请参阅SqlFiddle
修改
为您的问题
SELCT custInfo.CName,
Count(*) as TransactionCount,
SUM(CTotal) as TransactionTotal
FROM (TamarawTransaction trans
INNER JOIN TamarawCustomerInformation custInfo
ON trans.CCustomerCode=custInfo.CCustomerCode)
INNER JOIN TamarawTrip trip
ON trans.CTrip=trip.CTrip
Where trip.CStatus='Finalized'
AND trans.CStatus='Active'
GROUP BY custInfo.CName
使用“奇怪的访问连接语法”
SELECT TamarawCustomerInformation.CName,
Count(*) AS TransactionCount,
SUM(CTotal) AS TransactionTotal
FROM TamarawCustomerInformationn
INNER JOIN (TamarawTrip INNER JOIN TamarawTransaction ON TamarawTrip.CTrip=TamarawTransaction.CTrip)
ON TamarawCustomerInformationn.CCustomerCode=TamarawTransaction.CCustomerCode
WHERE TamarawTrip.CStatus='" & "Shipped" & "' and TamarawTransaction.CStatus='" & "Active" & "'
GROUP BY TamarawCustomerInformation.CName;