2012-10-17 26 views
1

我創建了一個視圖,我幾乎可以複製原始用戶的數據,但是我也有一個屬性,我想將用戶具有的出現次數下載表。根據where子句的結果創建別名

CREATE VIEW customer_count_streams_vw(
sid_customer 
systemuser_id 
postcode 
age 
gender 
num_streams) 
AS 
SELECT 
user.sid_customer, 
user.systemuser_id, 
user.postcode, 
user.age, 
user.gender, 
num_streams 
FROM md_customer 
INNER JOIN ods_streaming AS num_streams (
SELECT COUNT(ods_streaming.sid_customer) 
WHERE ods_streaming.sid_customer = md_customer.sid_customer) 

我要的是部分的結果放在:

SELECT COUNT(ods_streaming.sid_customer) 
WHERE ods_streaming.sid_customer = md_customer.sid_customer 

num_streams領域。

+0

'USER'是大多數(如果不是全部的話)數據庫引擎的保留字 –

+0

謝謝。這只是代碼的草稿,所以我最終將其更改爲其他內容。 – olovholm

回答

1

您的查詢應該是

SELECT 
user.sid_customer, 
user.systemuser_id, 
user.postcode, 
user.age, 
user.gender, 
num_streams 
FROM md_customer 
INNER JOIN 
( 
     SELECT sid_customer, COUNT(ods_streaming.sid_customer) num_streams 
     FROM ods_streaming group by sid_customer 
) AS ods_streaming 
ON ods_streaming.sid_customer = md_customer.sid_customer 

上面的查詢將返回ods_streaming行可爲客戶提供在md_customer行並一行。如果您希望所有客戶和他們的數(包括0),那麼您的查詢應該是

SELECT 
cust.sid_customer, 
cust.systemuser_id, 
cust.postcode, 
cust.age, 
cust.gender, 
COUNT(strm.sid_customer) num_streams 
FROM 
    md_customer cust 
LEFT OUTER JOIN ods_streaming strm 
    ON cust.sid_customer = strm.sid_customer 
group by 
cust.sid_customer, 
cust.systemuser_id, 
cust.postcode, 
cust.age, 
cust.gender 
+0

這看起來不太正確。在num_streams之前不應該有一個AS,如'COUNT(ods_streaming.sid_customer)AS num_streams'? –

+0

不,你不需要'as'來爲列名使用別名。這不是必需的。 –

+0

我對命令做了一些修改,但是這幫助我理解了這個概念。謝謝。 – olovholm

0

也許你可以嘗試使用組的數量,而不是一個子選擇。

SELECT 
md_customer.sid_customer, 
md_customer.systemuser_id, 
md_customer.postcode, 
md_customer.age, 
md_customer.gender, 
count(ods_streaming.num_streams) 
FROM md_customer 
INNER JOIN ods_streaming 
on ods_streaming.sid_customer = md_customer.sid_customer 
group by 1,2,3,4,5; 

你應該避免做子選擇這樣的......這組由應使事情更快一點

0
SELECT 
    u.sid_customer, 
    u.systemuser_id, 
    u.postcode, 
    u.age, 
    u.gender, 
    num_streams.amount 
FROM 
    md_customer u INNER JOIN (
      SELECT 
       ods_streaming.sid_customer, 
       COUNT(ods_streaming.sid_customer) as amount 
      FROM 
       ods_streaming 
      GROUP BY ods_streaming.sid_customer 

     ) num_streams ON (num_streams.sid_customer = u.sid_customer) 

除了:用戶是保留字在大部分,如果不是所有數據庫引擎