如何计算sum大于x的数据

时间:2012-02-02 12:21:50

标签: sqlite count having-clause

我是SQL的新手,我正在使用SQLite 3对销售数据进行购物篮分析。

相关列是产品ID,唯一交易ID(用于标识购物篮)和产品数量。如果客户购买了多种产品类型,则重复使用unqiue交易ID。

我想要计算顾客购买1件物品的篮子数量。

到目前为止,我已尝试select count(distinct uniqID) from salesdata having sum(qty) = 1;

但这引起了一个错误a GROUP BY clause is required before HAVING

然后我尝试了select count(distinct uniqID) from salesdata group by uniqID having sum(qty) = 1

SQlite接受了这个,但是给了我一个只有1的列表,这也不对!

然后我尝试了select count(uniqID) from salesdata group by qty having sum(qty) = 1

SQlite也接受了这一点,但一无所获。

任何想法都会非常感激!

电子

2 个答案:

答案 0 :(得分:3)

尝试这样的方法来检索每个在篮子中有多于或等于一个项目的用户

select uniqID, sum(qty) as total from salesdata group by uniqID having total >= 1

如果您想让只有在其购物篮中有1件商品的用户将>=1替换为=1

像:

select uniqID, sum(qty) as total from salesdata group by uniqID having total = 1

如果你想要在他们的篮子中有1个项目的用户数量,你可以这样:

SELECT COUNT(*) FROM (select uniqID, sum(qty) as total from salesdata group by uniqID having total 
= 1)

答案 1 :(得分:0)

选择只有一个项目的篮子数量。这也将过滤掉一个数量大于一个项目的篮子。如果您不想这样,请删除WHERE qty = 1部分。

  SELECT 
    COUNT(uniqID)    FROM 
    (SELECT 
      uniqID, SUM(qty) AS total 
     FROM 
      salesdata 
     WHERE 
       qty = 1 
     GROUP BY 
       uniqID 
     HAVING 
       total = 1)