表变量/ CTE的SQL帮助

时间:2015-03-27 07:18:03

标签: sql sql-server tsql

大师, 我有一张桌子,上面记录了所有顾客的购物详情,如下所示。 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
  2. 上显示每位客户的一条记录
    1/1/2011  a  0
    1/1/2011  a  1
    1/1/2011  b  0
    
    1. 在给定的日期范围内(1/1/2011- 3/1/2011),需要最近的商店日期具有customerid + shopmode的唯一价值
    2. 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
      2. 3/1/2011   a   1    
        3/1/2011   b   0    
        3/1/2011   c   0
        

        需要你的帮助..

        SELECT Max(shopdate),customerid, shopmode
        FROM Table 
        

        有了这个结果,我将加入shoppingdetail表来显示数据。创建一个表变量或CTE显示我可以与其他表连接。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

试试这个:

    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;