1

I have a query join 2 table as below:

SELECT * FROM Staff s INNER JOIN Account a on s.AccNo = a.AccNo WHERE a.Status = 'Active'

The result as shown:

 AccNo | Name | ID
 ------------------ 
   1   | Alex | S01
   2   | John | S02

After I get the staff ID,I write second query to find out the max sale as below:

SELECT s.ProductID,Max(s.Amount) from Sales s WHERE StaffID = 'S01' GROUP BY s.ProductID

The max sale for Staff 'S01' as below:

ProductID  | Amount
------------------
   Cloth   | 2000

How to I combine these 2 queries and become result as below? Thanks

 AccNo | Name | ID | Amount
 -------------------------- 
   1   | Alex | S01 | 2000
   2   | John | S02 | 5000
4

4 回答 4

1

您可以创建一个子查询并加入它:

SELECT a.AccNo, b.Name, b.ID, c.maximum 
FROM transaction as a 
INNER JOIN Account as b 
ON a.AccNo = b.AccNo
LEFT JOIN (SELECT StaffID, Max(Amount) as maximum FROM Sales GROUP BY StaffID) as c 
ON c.StaffID = b.ID
WHERE b.Status = 'Active'

请参阅SQLFiddle 示例(我试图猜测架构)

于 2013-09-05T06:55:12.973 回答
0

所以你想要做的是加入staffId然后组的销售。

SELECT a.AccNo,a.Name,a.ID,Max(s.Amount) 
FROM Transaction t 
INNER JOIN Account a on t.AccNo = a.AccNo 
INNER JOIN Sales s on s.staffId = a.ID
WHERE a.Status = 'Active'
GROUP BY a.AccNo,a.Name,a.ID
于 2013-09-05T06:44:06.577 回答
0

你可以尝试这样的事情:

Select Account.*, Max(Sales.amount) from Sales 
JOIN Account ON Sales.StaffID = Account.ID 
where Account.status = 'Active'
group by Sales.ProductID, Account.AccNo, Account.Name, Account.ID

老实说,我不明白您为什么在查询中使用 Transascation 表,因为您不使用它。

于 2013-09-05T06:53:16.660 回答
0

我认为这应该有效

只需加入并检索与每个员工相关的最大数量

SELECT t.AccNo , t.Name, t.ID, s.ProductID, Max(s.Amount) FROM Transaction t

INNER JOIN 帐户 a ON t.AccNo = a.AccNo

INNER JOIN Sales s ON s.StaffID = a.ID

WHERE a.Status = '活动';

谢谢

于 2013-09-05T07:08:47.850 回答