2015-08-19 46 views
2

我有如下表:如何通過做1組並計算SQL子查詢個人組

date_trans | customerId 
2015-02-01 | 12 
2015-02-01 | 14 
2015-02-01 | 13 
2015-02-01 | 12 
2015-02-02 | 13 
2015-02-02 | 12 
2015-02-02 | 13 
2015-02-02 | 14 
2015-02-02 | 14 

我能夠有一批獲得每日總交易方式:

SELECT date_trans, COUNT(*) as "Transactions" FROM theTable GROUP BY date_trans 

date_trans | Transactions 
2015-02-01 | 4 
2015-02-02 | 5 

但我不能夠通過客戶從同日起部分號碼:

date_trans | Transactions | "By 12" | "By 13" | "By 14" 
2015-02-01 | 4   | 2  | 1  | 1 
2015-02-02 | 5   | 1  | 2  | 2 

我試着做一組由選擇但它不起作用。

我如何在SQL 2014中實現這一點?

謝謝

+3

沒有「動態SQL」 *(代碼寫入SQL)*你不能僅僅因爲你的數據改變了不同的列數。你*可以*做你所描述的事情,只要你總是***和***只***想要爲那些三個特定的客戶***轉移數據?或者,每個客戶每天的結果集爲一行? *(使用名爲'date_trans,customerId,transaction_count'的列)* – MatBailie

+0

這種情況實際上是靜態客戶,能夠動態地執行此操作會很好。通過將customer_id添加到GROUP BY子句中,可以實現每個客戶每天一行的結果集。 – Felix

回答

3
with trans as (
SELECT date_trans, COUNT(*) as "Transactions" 
FROM theTable 
GROUP BY date_trans) 
, cust as (
SELECT customerid, date_trans, COUNT(*) as "cust_txns" 
FROM theTable 
GROUP BY customerid, date_trans) 
select c.date_trans, 
     t.transactions, 
     case when c.customerid = 12 then cust_txns end as "By 12", 
     case when c.customerid = 13 then cust_txns end as "By 13", 
     case when c.customerid = 14 then cust_txns end as "By 14" 
from trans t join cust c 
on t.date_trans = c.date_trans 

這是做這件事。但是,如果您有許多客戶,則必須使用動態SQL。

編輯:要消除行上的空值,需要更多級別的分組,如下所示。

with trans as (
SELECT date_trans, COUNT(*) as "Transactions" 
FROM thetable 
GROUP BY date_trans) 
, cust as (
SELECT customerid, date_trans, COUNT(*) as "cust_txns" 
FROM thetable 
GROUP BY customerid, date_trans) 
select c.date_trans, 
     max(t.transactions) as transactions, 
     max(case when c.customerid = 12 then cust_txns end) as "By 12", 
     max(case when c.customerid = 13 then cust_txns end) as "By 13", 
     max(case when c.customerid = 14 then cust_txns end) as "By 14" 
from trans t join cust c 
on t.date_trans = c.date_trans 
group by c.date_trans 

SQL Fiddle

+0

很好的答案,但它每天給我3行,數據不會每天合併爲一行。正確的結果在那裏,但其他列是NULL – Felix