Max with Having子句

时间:2018-03-20 16:28:53

标签: mysql sql

我有这个数据库

Game(ID,Version,Name,Price,Color,IDDISTRIBUTION,#worker)
Distribution(ID,Name,#worker,quality)  
Istitute(ID,Name,NINCeo,City)  
Sponsor(IDGAME,IDISTITUTE,VERSIONGAME)  
Designer(NIN,name,surname,role,budget)
Project(NINDESIGNER,IDGAME,VERSIONGAME,#hours)

(大写用于表示外键)

我必须在SQL中编写这个嵌套查询:

  • 选择赞助最大数量的Istitute 游戏(姓名,#max_games)
  • 选择赞助分钟的Istitute 游戏数量(名称,#min_games)
  • 选择已拍摄的设计器 参加近10场比赛(NIN,#game)

(在括号中是要选择的行,#是COUNT查询的结果)

非常感谢你的回答,对不起我的英语不好。

3 个答案:

答案 0 :(得分:1)

嘿,我知道很难获得有关如何正确提问的反馈意见,我已经去过那里了!尝试更清楚地编写问题并格式化,以便于理解。

据说,看看窗口功能!它们真的很酷,可以让你做有趣的分析,例如谁拥有第三多的游戏?试试这个:

with counts as (
    select
    i.id
    ,i.name
    ,count(distinct g.id) as gamecount
    from istitute i
    inner join games g
    on i.id=g.id
    and i.name=g.name
    group by i.id
    ,i.name
)

select
c.id
,c.name
,RANK() over (ORDER BY c.gamecount DESC) as rank
from counts c

答案 1 :(得分:1)

a)选择赞助最多游戏次数的学生

;with TempCount as (
     select  IDISTITUTE,
            count(IDGAME) As GameCount 
     from Sponsor S 
     Group by  IDGAME,IDISTITUTE
    )

    select Top  1
    T.IDISTITUTE,
    Count(T.GameCount) As  MaxGameCount
    from TempCount T 
    Group  by T.IDISTITUTE order  by Count(T.GameCount) desc

b)选择赞助最少数量游戏的学生

 ;with TempCount as (
     select  IDISTITUTE,
            count(IDGAME) As GameCount 
     from Sponsor S 
     Group by  IDGAME,IDISTITUTE
    )

    select Top  1
    T.IDISTITUTE,
    Count(T.GameCount) As  MinGameCount
    from TempCount T 
    Group  by T.IDISTITUTE order  by Count(T.GameCount) asc

答案 2 :(得分:0)

我认为我找到了解决方案:

sample_and_get_below <- function(df, when, size){
  res <- filter(df, calWeek == when) %>%
    sample_n(size)
  filter(df, calWeek > when) %>%
    rbind(res, .)
}
sample_and_get_below(dat, 201741, 1)
  ids months calWeek value
1   2     88  201741    99
2   2     88  201742   100
3   2     88  201743  1001
4   2     88  201744  1002

b)与a)相同,但是MIN

a)SELECT Name,#max_game
  FROM Istitute
  WHERE(SELECT COUNT (IDGAME) as #max_game
  FROM Sponsor,Game,Istitute
  WHERE(IDGAME=Game.id AND IDISTITUTE=Istitute.id AND VERSIONGAME=Game.Version))
  HAVING=(SELECT MAX COUNT (IDGAME) as #realmax_game)
  FROM Sponsor,Game,Istitute
  WHERE(IDGAME=Game.id AND IDISTITUTE=Istitute.id AND VERSIONGAME=Game.Version))