我参加了一系列T-SQL练习测试。除了其中一个,我做得很好。我拍了一张照片,以便稍后找出正确的答案。我不认为自己是专家,但我知道我的方式围绕SQL。然而,我不能写出一个不那么难以提出的问题。
以下是练习:
我可能需要按名称分组并总结价格,但我仍然有点迷失。帮助这一个!谢谢
答案 0 :(得分:3)
我会这样做:
SELECT
people.name,
sum(case when sales.fk_people is not null then 1 else 0) as total_sales,
sum(coalesce(sales.price,0.0)) as total_amount
FROM people
LEFT JOIN sales ON people.id = sales.fk_people
GROUP BY people.id
-- Could also be ORDER BY sum(coalesce(sales.price,0.0)) desc
ORDER BY people.id;
答案 1 :(得分:1)
这是一个非常简单的GROUP BY,带有COUNT()和SUM()。这两个表也需要加入:
SELECT name, count(*) as total_sales, sum(price) as total_amount
FROM people INNER JOIN sales ON people.id = sales.fk_people
GROUP BY name;
答案 2 :(得分:0)
你也可以试试这个
SELECT
p.Name
,ISNULL(s.Total_Sales,0) AS Total_Sales
,ISNULL(s.Total_Amount,0) AS Total_Amount
FROM people p
LEFT JOIN
(
SELECT
fk_people
,COUNT(*) AS Total_Sales
,SUM(Price) AS Total_Amount
FROM Sales
GROUP BY fk_people
) s ON p.ID = s.fk_people