2012-02-29 103 views
0

是否有可能從同一個表得到的結果如下日期明智記錄:多個子查詢

   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, 
    Enroll = (Select COUNT(*) from tblCustomer where field1 <> '' group by created), 
    Email = (Select COUNT(field1) from tblCustomer where field1 = 'E-mail' and field1  <> '' group by created), 
    Cell = (Select COUNT(*) from tblCustomer where field1 = 'Cell Phone' and field1 <> '' group by created) 
from tblCustomer 
group by created 
order by created 
+0

什麼是你的數據庫/表結構? – 2012-02-29 10:30:59

+0

桌子是什麼樣的?沒有相關信息的人應該如何回答這個問題? – 2012-02-29 10:31:46

+0

請詳細說明。你是指含有日期的記錄嗎?或者是其他東西? – 2012-02-29 10:32:46

回答

2

嘗試:

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 d 
     where d.created = c.created_date and 
       d.DishoutResponseCode = '0000') Deals_Redeemed 
from tblCustomer c 
group by created_date 
order by created_date 
+0

它給我相同的行用於所有日期... – 2012-02-29 11:08:44

+0

@VishalSuthar:現在怎麼樣? – 2012-02-29 11:13:50

+0

請檢查我的問題..我已通過添加我目前的查詢不起作用來更新它。 – 2012-02-29 11:17:25

3

你不想COUNT(),而是一個SUM(CASE/WHEN)

Select 
     Created, 
     count(*) TotalCnt, 
     SUM(CASE WHEN Field1 = 'E-mail' then 1 else 0 END) as EMailCnt, 
     SUM(CASE WHEN Field1 = 'Cell Phone' then 1 else 0 END) as CellCnt, 
     SUM(CASE WHEN RedeamedCondition then 1 else 0 END) as RedeamCnt 
    from 
     tblCustomer 
    group by 
     created 
    order by 
     created 

注意......如果創建一個日期/時間,您將需要有組通過僅基於「已創建」的日期部分,否則每秒會得到不同的計數...從另一篇文章中,通過基本上刪除小時,以下僅獲取日期時間的日期部分:分鐘:秒部分

DATEADD(dd, 0, DATEDIFF(dd, 0, created)) 

或者如果沒有意義,您可以通過

datepart(yy, created) as GrpYear, 
datepart(mm, created) as GrpMonth, 
datepart(dd, created) as GrpDay, ... rest of columns.....