是否可以通过分组多个列来获取一行(Is it possible to get one row by grouping more than one column)

编程入门 行业动态 更新时间:2024-10-20 16:24:40
是否可以通过分组多个列来获取一行(Is it possible to get one row by grouping more than one column)

我有一个查询如下。 数据库来自http://www.w3schools.com/sql/default.asp

SELECT count(distinct C.CustomerID),C.Country FROM Customers C inner join Orders O on C.CustomerID = O.CustomerID inner join OrderDetails D on O.OrderID = D.OrderID inner join Products P on D.ProductID = P.ProductID group by C.Country,P.CategoryID order by C.Country

这是上面的结果。

但我想通过计算CustomerID来获得每个国家的一行(如下图所示),其中任何CustomerID在同一个国家/地区并且具有相同的CategoryID。 所以我必须按2列分组。 有什么办法吗? 请你帮我一下吗?

谢谢。

I have a query as below. DB from http://www.w3schools.com/sql/default.asp

SELECT count(distinct C.CustomerID),C.Country FROM Customers C inner join Orders O on C.CustomerID = O.CustomerID inner join OrderDetails D on O.OrderID = D.OrderID inner join Products P on D.ProductID = P.ProductID group by C.Country,P.CategoryID order by C.Country

Here is the result from above.

But I want to get one row per country(as below pic) by counting CustomerIDs where any CustomerIDs are in the same country and have a same CategoryID as well. So I have to group by 2 columns. Is there any way to do it? Could you please kindly suggest me?

Thank you.

最满意答案

这很简单。 只需删除GROUP BY子句中的P.CategoryID 。

SELECT COUNT(DISTINCT C.CustomerID), C.Country FROM Customers C INNER JOIN Orders O ON C.CustomerID = O.CustomerID INNER JOIN OrderDetails D ON O.OrderID = D.OrderID INNER JOIN Products P ON D.ProductID = P.ProductID GROUP BY C.Country ORDER BY C.Country;

更新

在您的评论之后,这应该是正确的方法:

SELECT T.Country, SUM(T.Cnt) FROM ( SELECT COUNT(DISTINCT C.CustomerID) AS Cnt, C.Country FROM Customers C INNER JOIN Orders O ON C.CustomerID = O.CustomerID INNER JOIN OrderDetails D ON O.OrderID = D.OrderID INNER JOIN Products P ON D.ProductID = P.ProductID GROUP BY C.Country, P.CategoryID ) AS T GROUP BY T.Country ORDER BY T.Country;

That's quite simple. Just remove P.CategoryID in your GROUP BY clause.

SELECT COUNT(DISTINCT C.CustomerID), C.Country FROM Customers C INNER JOIN Orders O ON C.CustomerID = O.CustomerID INNER JOIN OrderDetails D ON O.OrderID = D.OrderID INNER JOIN Products P ON D.ProductID = P.ProductID GROUP BY C.Country ORDER BY C.Country;

Update

Following your comment, this should be correct approach then:

SELECT T.Country, SUM(T.Cnt) FROM ( SELECT COUNT(DISTINCT C.CustomerID) AS Cnt, C.Country FROM Customers C INNER JOIN Orders O ON C.CustomerID = O.CustomerID INNER JOIN OrderDetails D ON O.OrderID = D.OrderID INNER JOIN Products P ON D.ProductID = P.ProductID GROUP BY C.Country, P.CategoryID ) AS T GROUP BY T.Country ORDER BY T.Country;

更多推荐

本文发布于:2023-04-29 10:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336330.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   可以通过   row   grouping   column

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!