我有两张桌子;成员和流。 我想找到所有成员的平均流数,然后查看哪些成员(包括名字)的流量超过平均流量。
目前我有这个查询,它可以找到每个成员的平均流数和流数;
select stream.m_ID, count(*), (select avg (count(*)) from stream group by stream.m_ID) from stream group by stream.m_ID;
我正在努力找到如何丢弃流量低于平均数量的成员并且加入成员和流表一起
CREATE TABLE "M_5006677"."MEMBER"
( "M_ID" NUMBER(2,0),
"FNAME" VARCHAR2(15 BYTE) NOT NULL ENABLE,
"MNAME" VARCHAR2(15 BYTE),
"LNAME" VARCHAR2(15 BYTE) NOT NULL ENABLE,
"EMAIL" VARCHAR2(25 BYTE) NOT NULL ENABLE,
"R_DATE" DATE NOT NULL ENABLE,
"L_DATE" DATE,
CONSTRAINT "PK_M_ID" PRIMARY KEY ("M_ID")
CREATE TABLE "M_5006677"."STREAM"
( "STREAM_ID" NUMBER(2,0),
"SDATE" DATE,
"SPOSITION" NUMBER(5,2),
"F_ID" NUMBER(2,0) NOT NULL ENABLE,
"M_ID" NUMBER(2,0) NOT NULL ENABLE,
"LIVE" VARCHAR2(3 BYTE),
CONSTRAINT "PK_STREAM" PRIMARY KEY ("STREAM_ID")
CONSTRAINT "FK_F_ID" FOREIGN KEY ("F_ID") REFERENCE FILM
CONSTRAINT "FK_M_ID" FOREIGN KEY ("M_ID") REFERENCE MEMBER
答案 0 :(得分:2)
我会使用窗口函数。如果您只想计算曾经流式传输的成员:
select m_id
from (select m_id, count(*) as cnt, avg(count(*)) over () as avg_overall
from streams
group by m_id
) s
where cnt > avg_overall;
如果您想要计算从未流式传输的成员:
select m_id
from (select m_id, count(*) as cnt, avg(count(s.m_id)) over () as avg_overall
from members m left join
streams s
on m.m_id = s.m_id
group by m_id
) s
where cnt > avg_overall;
答案 1 :(得分:0)
这适用于sql server:
select stream.m_ID, count(*), (select avg (count(*)) from stream group by stream.m_ID) from stream group by stream.m_ID
having count(*) < (select avg (count(*)) from stream group by stream.m_ID)
如果您还想获取有关成员的数据,那么您应该在查询中包含M_ID,以便您可以像这样加入成员表:
select stream.m_ID, M_ID, count(*), (select avg (count(*)) from stream group by stream.m_ID) from stream group by stream.m_ID ,M_ID
having count(*) < (select avg (count(*)) from stream group by stream.m_ID)
之后,您可以使用Members表加入M_ID:
select FNAME from Member m
join (select stream.m_ID, M_ID, count(*), (select avg (count(*)) from stream
group by stream.m_ID) from stream group by stream.m_ID ,M_ID
having count(*) < (select avg (count(*)) from stream group by
stream.m_ID)) X on m.M_ID = X.M_ID