【问题标题】:SQL help for table variable/CTE表变量/CTE 的 SQL 帮助
【发布时间】:2015-03-27 15:54:48
【问题描述】:

大师们, 我有一张表,其中记录了所有客户的购物详细信息,如下所示。 shopmode 是主表 ID。

ShopDate    CustomerId  ShoppingMode
1/1/2011    a                  0
1/1/2011    a                  0
1/1/2011    a                  1
1/1/2011    b                  0
2/1/2011    a                 0
2/1/2011    b                 1
3/1/2011    a                 1
3/1/2011    b                 0
3/1/2011    c                0

我正在尝试查询需求 (日期为 dd/mm/yyyy)

  1. 在 shopdate、customerid、shopmode 上为每位客户显示一条记录
1/1/2011  a  0
1/1/2011  a  1
1/1/2011  b  0
  1. 在给定的日期范围内(2011 年 1 月 1 日-2011 年 3 月 1 日),需要具有唯一值 customerid + shopmode 的最近商店日期
3/1/2011  a    1
3/1/2011  b    0
3/1/2011  c    0
2/1/2011  b    1
2/1/2011  a    0
  1. 在给定的日期范围内 (1/1/2011-3/1/2011),按 shopdate 为 customerid 的最新日期
3/1/2011   a   1    
3/1/2011   b   0    
3/1/2011   c   0

需要你的帮助..

SELECT Max(shopdate),customerid, shopmode
FROM Table 

有了这个结果,我将加入 shoppingdetail 表以显示数据。我正在尝试创建一个表变量或 CTE 显示我可以加入其他表。

【问题讨论】:

  • 能否提供预期的输出?
  • 使用row_number()over(partition by ....)

标签: sql sql-server tsql


【解决方案1】:

1:只是分组或选择不同

with cte1 as (
select ShopDate, CustomerId, ShoppingMode
from table
group by  ShopDate, CustomerId, ShoppingMode)
select * from cte1;

2:首先,查找每天购物类型和客户的数量。那么对于那些只有一种购物类型的人,只需获得最大日期即可。

with cte2 as (
select ShopDate, CustomerId, max(ShoppingMode), 
      count(distinct ShoppingMode) as cnt
from table
where ShopDate between start_date and end_date
group by  ShopDate, CustomerId
)
select max(ShopDate)as ShopDate, CustomerId, ShoppingMode
from cte2
where cnt = 1
group by Customer_id;

3:只需选择所有客户,对他们进行排名,然后选择您想要的:

with cust as (   
select 
     CustomerId, 
     row_number() over (partition by customerId order by ShopDate desc) as rnk
from table 
where ShopDate between start_date and end_date
)
select * from cust where rnk = 1

【讨论】:

  • 我有大约 1900 万条记录.. group by 会很重.. 任何其他选项
  • 我没有看到更好的选择。如果您有很多行,请使用并行提示。此外,ShopDate 上的索引应该对第二个和第三个查询有用。
【解决方案2】:

试试这个:

    SELECT *
  FROM (SELECT ShopDate,
               CustomerId,
               ShoppingMode,
               ROW_NUMBER ()
                  OVER (PARTITION BY ShopDate, CustomerId, ShoppingMode
                        ORDER BY ShopDate, CustomerId, ShoppingMode)
                  rn
          FROM yourtable where shopdate >= '01jan2011' AND shopdate <= '03jan2011')
 WHERE rn = 1;

【讨论】:

  • 对于其他 2 个选项,我们也可以使用 partition by
  • 对于其他 2 个选项,意味着另外两个字段?如果字段,那么您可以在 partition by 子句中添加,也可以在 order by 子句中添加。
猜你喜欢
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 1970-01-01
  • 2011-04-21
  • 2011-05-04
  • 1970-01-01
相关资源
最近更新 更多