在现有子查询中添加SubQuery

时间:2012-03-03 09:37:49

标签: sql-server sql-server-2008 sql-server-2005

表结构:
tblCustomer

Customer_id  created   field1      field2        cardno
--------------------------------------------------------    
1014     Test1     Cell Phone  123146        1234567890
1015     Test2     Email       abc@xyz.com   2345678891

tbl_TransactionDishout

Trnx_id   offerNo   TerminalID      Created                  cardno
-------------------------------------------------------------------
1         1014      170924690436418 2010-05-25 12:51:59.547  1234567890

是否可以将结果作为以下日期记录获取:

               Enrolled   Enrolled as Email  Enrolled as Text Deals Redeemed   
<First Date>   7          5                  2                6
<Next Date>    9          3                  6               14

我当前的查询是这样的:

select created,
count(field1) Enrolled,
count(case field1 when 'E-mail' then 1 end) Enrolled_as_Email,
count(case field1 when 'Cell Phone' then 1 end) Enrolled_as_Cell
from tblCustomer c
group by created 
order by created desc

但是它给了我仅包含在tblCustomer表中的日期结果..

现在,如何获得Deals_redeemed ..? tbl_transaction和tblCustomer之间的关系具有相同的cardno ...

1 个答案:

答案 0 :(得分:1)

在我的理解表中,tbl_TransactionDishout是一个提议,如果跟着一个记录将被插入到tblCustomers中;如果没有,没有什么会改变。因此,兑换的交易是tblCustomers中针对给定cardno的不存在记录的计数:

select t.created,
   count(c.field1) Enrolled,
   count(case c.field1 when 'E-mail' then 1 end) Enrolled_as_Email,
   count(case c.field1 when 'Cell Phone' then 1 end) Enrolled_as_Cell,
   count(case when c.field1 is null then 1 end) [Deals Redeemed]
from tbl_TransactionDishout t left join tblCustomer c 
   on t.cardno = c.cardno
group by t.created
order by t.created desc

编辑:c.created已更改为t.created