我是SQL的新手,我正在使用SQLite 3对销售数据进行购物篮分析。
相关列是产品ID,唯一交易ID(用于标识购物篮)和产品数量。如果客户购买了多种产品类型,则重复使用unqiue交易ID。
我想计算客户购买1件,2件,3件,4件,5件和5件以上商品的篮子数量,以便分析只购买1件商品的客户百分比。
我使用的代码是:
select count (*) as One from (select uniqID, sum(qty) as total from otcdata3 group by uniqID having total > 0) where total = 1;
select count (*) as Two from (select uniqID, sum(qty) as total from otcdata3 group by uniqID having total > 1) where total = 2;
select count (*) as Three from (select uniqID, sum(qty) as total from otcdata3 group by uniqID having total > 1) where total = 3;
select count (*) as Four from (select uniqID, sum(qty) as total from otcdata3 group by uniqID having total > 1) where total = 4;
select count (*) as Five from (select uniqID, sum(qty) as total from otcdata3 group by uniqID having total > 1) where total = 5;
select count (*) as Six from (select uniqID, sum(qty) as total from otcdata3 group by uniqID having total > 1) where total = 6;
select count (*) as Sevenplus from (select uniqID, sum(qty) as total from otcdata3 group by uniqID having total > 1) where total > 6;
此代码确实有效,但首先,正如您所看到的,它看起来相当笨拙,其次,当我在Excel中打开数据时,数据会以下列格式显示:
One
1353697
Two
483618
Three
166148
Four
76236
Five
35079
Six
18904
Sevenplus
27896
理想情况下,我希望顶部的项目数量,以及满足该标准的篮子数量。虽然我现在可以手动将问题排除在外,但我需要尽快进行类似的分析!
关于如何编写代码以便按照我想要的方式构建代码的任何建议都将非常感谢!
答案 0 :(得分:0)
这就是你要找的东西:
select
case
when total=1 then 'One'
when total=2 then 'Two'
when total=3 then 'Three'
when total=4 then 'Four'
when total=5 then 'Five'
when total=6 then 'Six'
when total=7 then 'SevenPlus'
end,
count(total)
from
(select case when count(uniqID) <= 6 then count(uniqID) else 7 end as total from otcdata3 group by uniqID) as totals
group by total
order by total
这将返回两列,第一列是表示交易中项目数的文本,第二列是具有该项目数的不同购买数。