具有2个属性和1个条件分组的sql程序(导入)

具有2个属性和1个条件分组的sql程序(导入),sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有一个包含糖果发布数据的文本文件。 文件包含客户id、发行日期、糖果名称。 C12014-01-01,Candy1 C12014-01-02,Candy2 C22002-06-01,Candy2 C12014-01-02,Candy3 C22002-06-01,Candy3 我想知道如何编写一个程序,创建一份同时发放的成对糖果的列表,即在同一天至少25次不同时间发放给同一客户。 提前谢谢 --create a table to hold our data create table Cand

我有一个包含糖果发布数据的文本文件。
文件包含客户id、发行日期、糖果名称。

C12014-01-01,Candy1
C12014-01-02,Candy2
C22002-06-01,Candy2
C12014-01-02,Candy3
C22002-06-01,Candy3

我想知道如何编写一个程序,创建一份同时发放的成对糖果的列表,即在同一天至少25次不同时间发放给同一客户。
提前谢谢

--create a table to hold our data
create table CandySales
(
    CustomerId nchar(2)
    , SaleDate Date
    , CandyId nvarchar(10)
)

--upload the data from the csv
bulk insert CandySales 
from 'c:\temp\myCsv.csv' 
with (fieldterminator = ',', rowterminator = '\n')

--query the data
;with cte as 
(
    select customerId, candyId, saleDate 
    from CandySales 
    group by customerId, candyId, saleDate 
    having COUNT(1) >= 25
)
select distinct 
  a.CandyId Item1
, b.CandyId Item2
from cte a
inner join cte b
on a.CandyId > b.CandyId
and a.SaleDate = b.SaleDate
and a.CustomerId = b.CustomerId
查询说明

  • cte创建了一个列表,列出了在同一天向同一客户销售了25种或25种以上的所有糖果
  • 包括
    distinct
    ,因为我们可能会为多个日期/客户返回同一对;每双我们只想要一次
  • a.CandyId>b.CandyId上的
    ,用于确保这对糖果包含彼此不同的糖果。我们使用
    而不是
    =
    以避免得到与
    item1
    item2
    相反的同一对
  • 然后,我们加入销售日期和客户日期,因为我们想要在同一天销售给同一客户的商品

太棒了,非常感谢。但是我有一个问题,上面使用的CandyId实际上是varchar,那么我们可以在连接条件中使用a.CandyId>b.CandyId吗?