是否可以通过分组多个列来获得一行

时间:2016-01-04 13:59:06

标签: sql oracle

我有一个查询如下。来自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

以上是上述结果 enter image description here

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

enter image description here 谢谢。

1 个答案:

答案 0 :(得分:0)

这非常简单。只需删除P.CategoryID条款中的GROUP BY即可。

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;