【问题标题】:Need to calculate No of time customer visit the shop需要计算顾客光顾店铺的次数
【发布时间】:2020-03-26 17:33:50
【问题描述】:

我需要计算客户光顾商店的次数。连同购买的物品。在这种情况下,客户访问商店 3 次并购买了 5 件商品。现在当我计算访问次数时,我的输出是 5。

下面是我尝试的查询:

select 
    Receipt_no,
    Customer,sales_item,
    Amount,
    sum(Amount) over (partition by customer) as total_sales,
    count(Receipt_No) over (partition by customer) as No_of_Visit 
from sales
left join customer where sales.Customer = customer.Customer

我的输出是

Receipt_No  Customer  sales_item  Amount  total_sales  No_of_Visit
5           C1        Item1       100     1200         5
5           C1        Item3       200     1200         5
5           C1        item4       200     1200         5
34          C1        item1       300     1200         5
35          C1        item2       400     1200         5

但我希望 No_of_Visit 为“3”

【问题讨论】:

  • 为什么您需要离开加入 TO 客户?没有相关客户,销售怎么可能存在?
  • 请阅读this,了解一些改进问题的技巧。

标签: sql sql-server tsql distinct window-functions


【解决方案1】:

我认为您需要明确的收据计数。那可能是:

count(distinct receipt_no) over (partition by customer) as No_of_Visit

但不幸的是,SQL Server 不支持窗口函数中的distinct。但是,您可以使用 dense_rank() 模拟它:

dense_rank() over (partition by customer order by receipt_no) 
    + dense_rank() over (partition by customer order by receipt_no desc) 
    - 1 as No_of_Visit

【讨论】:

  • 欢迎@Angel。如果我的回答正确回答了您的问题,请点击检查符号accept it...谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 2015-01-23
  • 2012-10-30
  • 2017-03-24
  • 2023-02-01
  • 2021-03-20
  • 1970-01-01
相关资源
最近更新 更多