1

我正在创建一个视图,其中几乎复制了原始用户的数据,但我还有一个属性,我想将用户在下载表中的出现次数放在其中。

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领域。

4

3 回答 3

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

上面的查询将返回 md_customer 中的行以及 ods_streaming 中的行的客户行。如果您想要所有客户及其计数(包括 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
于 2012-10-17T18:04:13.753 回答
0

也许您可以尝试使用 group by 进行计数,而不是子选择。

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;

你应该避免做像这样的子选择......这个 group by 应该让事情变得更快一点

于 2012-10-17T18:08:59.243 回答
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 )

此外:用户是大多数(如果不是全部)数据库引擎中的保留字

于 2012-10-17T18:09:14.717 回答