【问题标题】:SQL select with GROUP BY and COUNT?使用 GROUP BY 和 COUNT 进行 SQL 选择?
【发布时间】:2021-10-02 05:02:00
【问题描述】:

假设我有三个表来管理从我的网上商店购买的商品:

  • 产品:包含 ID、名称、价格列
  • 客户:列 ID、名称
  • 购买:包含 ProductID、CustomerID、PurchaseDate 列

现在,我将如何检索超过N 不同客户购买的产品?

我在 SQL Server 2019 试用版上尝试了以下操作,但在 COUNT 上出现语法错误。

SELECT ProductID, CustomerID, COUNT(*) as C    
FROM Purchases    
GROUP BY ProductID, CustomerID    
HAVING C > 100    
ORDER BY C DESC

更好的是,我将如何检索超过 N 不同客户在 30 天内购买的产品?

感谢任何帮助和/或指点。

【问题讨论】:

  • 您当前的架构不支持这一点,您没有存储购买的时间戳。在目前的情况下,无法根据数据范围过滤购买。
  • 请发布确切的错误信息

标签: sql sql-server tsql


【解决方案1】:

对于您当前的查询,您只是在计算每个客户购买每种产品的频率,因为您是按 productidcustomerid 的组合进行分组的。此外,您不能引用 HAVINGORDER BY 子句中计数的列别名

试试这个

declare @purchasedatelower datetime = dateadd(day, -30, getdate())
declare @purchasedateupper datetime = getdate()
declare @distinctcustomers int = 100

select productid, count(distinct customerid) as customercount
from purchases
where purchasedate between @purchasedatelower and @purchasedateupper
group by productid
having count (distinct customerid) >= @distinctcustomers
order by count(distinct customerid) desc

这将返回过去 30 天内至少有 100 位不同客户购买的所有产品,以及不同数量的客户。

【讨论】:

  • 这可以解决问题。非常感谢您的解释!
  • 我已经有了。我收到消息“感谢您的反馈!您需要至少 15 声望才能投票,但您的反馈已被记录。”
  • @KeineUrsache 您可以通过单击复选标记来接受答案。您(还)不能做的是通过点击向上箭头来投票赞成答案。
【解决方案2】:

尝试通过COUNT()订购它们

SELECT ProductID, CustomerID

FROM Purchases

GROUP BY ProductID, CustomerID

HAVING COUNT(*) > 100

ORDER BY COUNT(*) DESC

【讨论】:

  • 这更好,但我也得到了一个客户多次购买的物品。
【解决方案3】:

现在,我将如何检索超过 N 个不同客户购买的产品?

你会使用COUNT(DISTINCT):

SELECT ProductID, COUNT(DISTINCT CustomerID) as num_customers   
FROM Purchases    
GROUP BY ProductID    
HAVING COUNT(DISTINCT CustomerID) > 100    
ORDER BY COUNT(DISTINCT CustomerID) DESC;

如果您有特定时期,请在 GROUP BY 之前添加一个 WHERE 子句。

【讨论】:

    【解决方案4】:
    DECLARE @Popularity int = 1
    DECLARE @MonthsAgo int = 1
    
    SELECT p.ProductId, p.ProductName, pc.CustomersDistinct
    FROM (
        -- Sub-query to compute the aggregate.
        -- Count the number of distinct customers that purchased each product.
        SELECT ProductId, COUNT(DISTINCT CustomerId) AS CustomersDistinct
        FROM Purchases
        WHERE PurchaseDate >= DATEADD(MONTH, -@MonthsAgo, CURRENT_TIMESTAMP)
        GROUP BY ProductId
        HAVING COUNT(DISTINCT CustomerId) > @Popularity
    ) AS pc
        -- Now do JOINs to look up helpful values for the final SELECT list.
        INNER JOIN Products p ON pc.ProductId = p.ProductId
    ORDER BY 3 DESC
    

    【讨论】:

      猜你喜欢
      • 2021-03-25
      • 2015-10-30
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 2016-10-11
      • 2021-04-01
      相关资源
      最近更新 更多