我坚持这个问题,我一直在努力根据客户分组数据,但没有运气,任何人都可以提供帮助。
SELECT S.Name AS 'CstName',
S.MinPrice - SUM(coalesce(c.Balance,0)) AS 'Blc',
S.NumberOfItems AS 'Sold'
FROM Cst c, (
SELECT c.Name, c.address, c.Balance, (Min(s.Price)*i.Qty) AS MinPrice, SUM(i.Qty) AS NumberOfItems
FROM dbo.Cst AS c
INNER JOIN
dbo.Odr AS o ON c.Name = o.Cust
INNER JOIN
dbo.inc AS i ON i.Order_no = o.Order_No
INNER JOIN
dbo.spls AS s ON i.Item = s.Item
WHERE i.Item = s.Item AND o.Cust =c.Name
group by i.Qty, c.Name, c.Balance, c.address) S
GROUP BY S.Name,S.MinPrice, S.Address, S.Balance, S.NumberOfItems
结果应该只显示Tom Mary一次
CstName Blc Sold
Tom 207.69 1.00
Tom 210.00 12.00
Tom 224.45 10.00
Mary 217.47 6.00
Mary 237.54 12.00
答案 0 :(得分:1)
由于您希望按每个客户分组并显示一行,因此您需要在GROUP BY
因此,在您的SELECT
中,您应汇总S.MinPrice
和S.NumberOfItems
并将其从GROUP BY
SELECT S.Name AS 'CstName',
SUM(S.MinPrice) - SUM(coalesce(c.Balance,0)) AS 'Blc', -- Based on your need you can use any of the aggregation functions
MAX(S.NumberOfItems) AS 'Sold' -- Based on your need you can use any of the aggregation functions
...
GROUP BY S.Name