【问题标题】:SQL Server : compare the column COUNT of purchased products to UNSOLD productsSQL Server:将已购买产品的列 COUNT 与 UNSOLD 产品进行比较
【发布时间】:2015-12-04 03:12:10
【问题描述】:

如果我要问一个转储问题,我真的很抱歉,我正在尝试完成以下任务:“编写查询以仅列出那些从未购买过的产品(p_id、p_name、cat_name)。”

我有 2 张桌子:

  • ProductCategory (p_id, p_name, cat_id, cat_name, cat_description)
  • CustomerPreference (cust_id, cust_name, pp_id(purchasedproduct), rating)

所以我尝试编写查询同时执行COUNT(p_id) FROM ProductCategoryCOUNT(pp_id) FROM CustomerPreference,以便我可以比较它们并仅列出那些未售出的产品。

SELECT 
    PC.p_id, PC.p_name, PC.cat_name, COUNT(PC.p_id) AS no_of_purchases
FROM 
    ProductCategory PC, CustomerPreference CP
WHERE 
    PC.p_id = CP.pp_id
GROUP BY 
    PC.p_id, PC.p_name, PC.cat_name, PC.p_id
HAVING 
    COUNT(CP.pp_id) NOT IN COUNT(PC.p_id)
ORDER BY 
    no_of_purchases

我知道我的语法在这个查询中是错误的,但我希望你能看到我试图实现的逻辑,如果你能告诉我如何显示没有的产品列(p_id),我将不胜感激卖掉了。

【问题讨论】:

  • 第一个需要回答的问题..如何识别购买的产品?
  • CustomerPreferences 表中的 pp_id 包含与 PoductCategory 表中的 p_id 相同的值。所以这就是为什么我试图计算我拥有的所有产品 ID,然后比较/减去购买产品的数量
  • Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI JOIN 语法-92 SQL 标准(20 多年前),不鼓励使用它

标签: sql sql-server sql-server-2008 count compare


【解决方案1】:

要从一个表 (ProductCategory) 中获取另一表 (CustomerPreference) 中不存在的行,您可以使用 NOT EXISTS

SELECT pc.*
FROM ProductCategory pc
WHERE 
    NOT EXISTS(
        SELECT 1 
        FROM CustomerPreference
        WHERE pp_id = pc.p_id
    )

【讨论】:

  • 感谢您的解决方案和解释,帮助我理解:)
【解决方案2】:

永远不会出现在 CustomerPreference 表中的产品是:

SELECT PC.p_id, PC.p_name, PC.cat_name
FROM ProductCategory PC
LEFT JOIN CustomerPreference CP
ON PC.p_id = CP.pp_id
WHERE CP.pp_id IS NULL
ORDER BY PC.p_name

【讨论】:

  • 感谢您的帮助,一个问题:由于我在任何表中都没有列“no_of_purchases”,我如何更改查询以创建一个。例如当我做 COUNT(p_id) AS no_of_purchases
  • @AlexVahrushev 抱歉,这样订购是个错误 - 我已经更正了我的答案。在此查询中,所有 no_of_purchases 都将为零。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多