在现有子查询中添加另一个子查询

时间:2012-03-01 06:56:25

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

是否可以从相同的表日期记录中获得如下结果:

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

表结构如下所示:

Customer_id, field1, field2, responsecode, created_date

我当前的查询是这样的:

select created_date,
   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,
   count(responsecode) Deals_Redeemed
   from tblCustomer
   group by created_date
   order by created_date

哪个适用于前三列,但是对于四个列是“Deals redeemed”,这是来自另一个表的子查询。

Select COUNT(*) from tbl_TransactionDishout where DishoutResponseCode = '0000'

表结构如下:
表名是“tbl_TransactionDishout”

    [Trnx_ID] [int] IDENTITY(1,1) NOT NULL,    
    [OfferNo] [nvarchar](50) NULL,   
    [MerchantID] [nvarchar](50) NULL,    
    [TerminalID] [nvarchar](50) NULL,    
    [DishoutResponseCode] [nvarchar](50) NULL,    
    [Created] [datetime] NULL    

3 个答案:

答案 0 :(得分:1)

你能尝试这样吗? (Deals_Redeemed值对于所有行都是相同的,你说两个表之间没有关系)

select created_date,
    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,
    (Select COUNT(*) from tbl_TransactionDishout where DishoutResponseCode = '0000') as Deals_Redeemed
from tblCustomer
    group by created_date
    order by created_date

答案 1 :(得分:0)

如果你的tbl_TransactionDishout有一个加入你的tblCustomer的ID列,你应该能够做一个单独的查询,如

select created_date,
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,
cnt
from tblCustomer t, 
(select id, count(1) as cnt
from tbl_transactiondishout
group by id) tt
where t.id = tt.id
group by created_date
order by created_date

答案 2 :(得分:0)

也许是这样的:

select 
    created_date,
    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,
    (
        Select COUNT(*) 
        from tbl_TransactionDishout 
        where DishoutResponseCode = tblCustomer.responsecode
    ) as Deals_Redeemed
from 
    tblCustomer
group by 
    created_date
order by 
    created_date