我正在创建一个视图,其中我几乎复制了原始用户的数据,但我还有一个属性,我想在其中列出用户在下载表中出现的次数。
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 :(得分: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
答案 1 :(得分: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;
你应该避免做这样的子选择......这个小组应该让事情更快一点
答案 2 :(得分: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 )
此外:用户是大多数(如果不是全部)数据库引擎的保留字