2012-10-17 2 views
1

원본 사용자의 데이터를 거의 복제하는 뷰를 만들고 있지만 사용자가 가지고있는 항목의 수를 넣으려는 특성도 있습니다. 다운로드 테이블. num_streams 필드에where 절의 결과를 기반으로 별칭 만들기

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

: 내가 원하는 무엇

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) 

은 부품의 결과를 배치하는 것입니다.

+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

이것은보기에 좋지 않습니다. 'COUNT (ods_streaming.sid_customer) AS num_streams'처럼 num_streams 이전에 AS가 존재하지 않아야합니까? –

+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) 

조금을해야하여이 그룹 : 사용자가 아니라면, 대부분의 예약어입니다 모든, 데이터베이스 엔진