在一个列上应用 distinct 并在另一列上按 count 排序
Posted
技术标签:
【中文标题】在一个列上应用 distinct 并在另一列上按 count 排序【英文标题】:Apply distinct on one column and order by on another with count 【发布时间】:2022-01-09 05:03:49 【问题描述】:在 mysql DB 中我有
CustomerId productId modelNumber
CAnWgsN0 C9407R 300
CAnWgsN0 C5861W 300
CAnWgsN0 C9407R 400
CAnWgsN0 C5861W 600
CAnWgsN0 C9407R 300
KAuK9nB K3150Z 100
KAuK9nB6 K3150Z 100
我希望我的输出为
customerId productId modelNumber Count
CAnWgsN0 C9407R 300 2
CAnWgsN0 C9407R 400 1
CAnWgsN0 C5861W 300 1
CAnWgsN0 C5861W 600 1
KAuK9nB6 K3150Z 100 2
我正在尝试使用此查询,但没有得到想要的结果。如何在 modelNumber 上应用 distinct,然后按 productId 分组。
SELECT *
FROM (SELECT customerId, productId, COUNT(modelNumber) As count,
ROW_NUMBER() OVER (PARTITION BY modelNumber ORDER BY productId) AS RowNumber
FROM customers) AS a
WHERE a.RowNumber <=100 ;
它只返回一行。我也尝试过这个查询,但没有运气
SELECT productId, customerId, modelNumber, COUNT(modelNumber) AS count
FROM customers
WHERE modelNumber IN (SELECT DISTINCT modelNumber from customer ORDER BY productId);
【问题讨论】:
【参考方案1】:除非我遗漏了什么,否则你只想GROUP BY customerId, productId, modelNumber
WITH customers AS (
(SELECT 'CAnWgsN0' AS customerId, 'C9407R' AS productId, 300 AS modelNumber ) UNION ALL
(SELECT 'CAnWgsN0', 'C5861W', 300) UNION ALL
(SELECT 'CAnWgsN0', 'C9407R', 400) UNION ALL
(SELECT 'CAnWgsN0', 'C5861W', 600) UNION ALL
(SELECT 'CAnWgsN0', 'C9407R', 300) UNION ALL
(SELECT 'KAuK9nB6', 'K3150Z', 100) UNION ALL
(SELECT 'KAuK9nB6', 'K3150Z', 100))
SELECT customerId, productId, modelNumber, COUNT(*) AS count
FROM customers
GROUP BY customerId, productId, modelNumber;
【讨论】:
以上是关于在一个列上应用 distinct 并在另一列上按 count 排序的主要内容,如果未能解决你的问题,请参考以下文章