音乐会数据库的子查询

时间:2018-09-29 05:27:04

标签: sql oracle

我在Oracle DB中有一张Concert表,其中包含ID / City / Artist / Price属性。我正在尝试编写查询以查看某个城市是否见过三位相同的艺术家(这意味着我只需要检查是否有三位艺术家在该城市中至少有过一次活动)。

function test() {console.log('test');}

$('#btna').click(function(){
  $('#btnb').click(function() { test(); });
});

此查询的结果包含多个值;但是对数据的挖​​掘告诉我,对于某些城市来说这是不可能的。我这里的逻辑怎么了?

4 个答案:

答案 0 :(得分:3)

您似乎要说的是想要一个拥有至少3位不同艺术家的城市的清单,但是您提供的查询没有这样做,它仅以相同的方式将Concert表自身链接了3次。该链接将始终以相同的方式成功执行,并且本质上是非操作,因为它会询问表本身是否存在数据-对于至少一行的任何数据库表都是如此

这就是为什么您的逻辑不起作用,但对于查询却更像这样的原因的原因:

Select city from concert group by city having count(distinct artist)>= 3

可能更合适

答案 1 :(得分:0)

问题是每条记录都匹配,因此您需要确保例如找到的记录。 B查询与A,C和D查询找到的记录不同。您可以在此处使用联接:

select DISTINCT A.City 
from Concerts A
INNER JOIN CONCERTS B
  ON B.CITY = A.CITY AND
     B.ID <> A.ID
INNER JOIN CONCERTS C
  ON C.CITY = A.CITY AND
     C.ID <> A.ID
INNER JOIN CONCERTS D
  ON D.CITY = A.CITY AND
     D.ID <> A.ID;

SQLFiddle here

好运。

答案 2 :(得分:0)

您可以使用自连接和Desire适当的输出。

import pandas as pd

def sortTable(df):
    """
    Returns a pd.DataFrame with goals scored by teams, sorted by total goals.

    df: pd.DataFrame, raw dataframe taken from .csv.
    """
    # groups by the Home team name, sums the FTHG, resets the grouping object indexing
    home_goals = df.groupby(['HomeTeam'])[['FTHG']].sum().reset_index()

    # rename the HomeTeam column to 'Team', column shared by tables to be merged
    home_goals.rename(columns = {'HomeTeam': 'Team'}, inplace = True)

    # groups by the away team name, sums the FTAG, resets the grouping object indexing
    away_goals = df.groupby(['AwayTeam'])[['FTAG']].sum().reset_index()
    away_goals.rename(columns = {'AwayTeam': 'Team'}, inplace = True)

    # merge the 2 tables by the team name
    goals_table = pd.merge(home_goals, away_goals, on='Team')
    goals_table['FTG'] = goals_table['FTHG'] + goals_table['FTAG']

    return goals_table.sort_values('FTG', ascending=False)


""" ------ Run Function Example ------ """
df_old = pd.read_csv('path_to_csv')
df_new = sortTable(df_old)

我认为这对您有所帮助。

答案 3 :(得分:0)

您想要的城市曾看过三位相同艺术家。您应该在考虑group by。在这种情况下,您可以使用:

Select city, artist
from concert
group by city, artist
having count(*) >= 3;

如果您只想要发生这种情况的城市,但是您不关心艺术家:

select distinct city
from concert
group by city, artist
having count(*) >= 3;

select distinct是因为这座城市本可以举办3场以上的音乐会,而其中不止一位艺术家。

编辑:

根据您的评论,您需要三位特定的艺术家。这并不完全相同,也不清楚,因为您最初的问题没有显示任何歌手姓名。

您可以使用group by / having轻松地做到这一点:

select city
from concert
where artist in ('Kanye', 'Jay-Z', 'Kendrick')
group by city
having count(distinct artist) >= 3;