尝试编写一个查询,该查询将获取最高和最低收入,并显示帐户运行状况吗?

时间:2019-03-12 15:29:09

标签: mysql sql subquery

我们正在尝试编写一个向我们显示的查询:

收入最高和最低的程序并打印其帐户运行状况

这是我们必须开始的:

顶部

Select TOP 5 * From Health, Revenue
From Program_T, Account_T
Order by Revenue;

底部

Select BOTTOM 5 * From Health, Revenue
From Program_T, Account_T
Order by Revenue;

以下是表格:

Program_T表:

(AccountName varchar(150) not null unique,
ProgramID int not null,
Revenue int,
Advocates int,
Shares int,
Conversions int,
Impressions int,
LaunchDate date,
CSMID int not null,
constraint Program_PK primary key (AccountName, CSMID),
constraint Program_FK1 foreign key (AccountName) references Account_T(AccountName),
constraint Program_FK2 foreign key (CSMID) references CSM_T(CSMID));

Account_T表:

create table Account_T
(AccountName varchar(150) not null unique,
Health varchar(10) not null,
EcommercePlatform varchar(50),
CSMID int not null,
Industry varchar(50),
Amount int not null,
constraint Accounts_PK primary key (AccountName),
constraint Accounts_FK foreign key (CSMID) references CSM_T(CSMID));

3 个答案:

答案 0 :(得分:1)

在MySQL中获得TOP行的子句为LIMIT。您订购升序或降序以获取顶部或底部行。如您所愿,这意味着您要使用UNION ALL粘合两个查询。而且,由于每个查询都有一个ORDER BY子句,因此需要括号以向DBMS显示ORDER BY子句所指的内容。最后,您需要一个最终的ORDER BY子句,因为不能保证UNION ALL的结果是有序的。

select revenue, health
from
(
  (
    select p.revenue, a.health
    from program_t p
    join account_t a using (accountname)
    order by p.revenue asc limit 5
  )
  union all
  (
    select p.revenue, a.health
    from program_t p
    join account_t a using (accountname)
    order by p.revenue desc limit 5
  )
) glued
order by revenue;

从MySQL 8开始,您还可以使用ROW_NUMBER对行进行排名,这可能会更快也可能不会更快:

select revenue, health
from
(
  select
    p.revenue, a.health,
    row_number() over (order by p.revenue asc) as rn1,
    row_number() over (order by p.revenue desc) as rn2
  from program_t p
  join account_t a using (accountname)
) numbered
where rn1 <= 5 or rn2 <= 5
order by revenue;

对于连接,您可以使用上面显示的USING子句,也可以使用ON

from program_t p
join account_t a on a.accountname = p.accountname

答案 1 :(得分:0)

您想要UNION ALL

Select TOP (5) AT.Health, PT.Revenue
From Program_T PT INNER JOIN
     Account_T AT
     ON PT.AccountName = AT.AccountName 
Order by Revenue
LIMIT 5
UNION ALL
Select TOP (5) AT.Health, PT.Revenue
From Program_T PT INNER JOIN
     Account_T AT
     ON PT.AccountName = AT.AccountName
Order by Revenue DESC
LIMIT 5;

答案 2 :(得分:0)

我认为您找到了union all

select * from (
 select * from
 (Select  Health, Revenue 
From Program_T p join Account_T a on p.AccountName =a.AccountName 
Order by Revenue desc limit 5
 )a
 union all
 select * from 
(
Select  Health, Revenue  
From Program_T p join Account_T a on p.AccountName =a.AccountName 
Order by Revenue limit 5
)b) as w