Complex SQL calculated/Group Query

I am trying to write a complex aggregate query(s) to compile a standings table for a soccer league.
There are four related tables:
Matches
Goals
Players
teams
I have yet to finalize the database structure so I can add fields if necessary.
In the goals table I track the match that the goal was scored in and which player
scored it.
I am trying to create a query that will give me a standings table.
The fields I need to calculate are:
team name
Wins
Loses
Draws
For instance:  There was a match on 4/21/2012.  The players on HomeTeam(A) scored a combined 6 goals.  The players on AwayTeam(B) scored 1 goal (All stored in the Goals table).  Therefore, Hometeam won by a score of 6-1.  I need
a query that spits out:
Team                Wins          Losses          Draws         
Points
HomeTeam(A)      1                 0                 0                
3
AwayTeam(B)       0                 1                 0                 3
Wins are worth 3 Losses 0 and Draws 1 point each team.
I am a long time SQL admin, but I think the complexity of calculating this is a little beyong me.  I need some help to get where I need to be.

Okay, I haven't yet been able to figure out the draws because of the trouble of linking back to both teams, but here's what I have so far.
First, here is the test data:
Declare @tvMatches Table (
MatchID int IDENTITY(1,1)
,MatchDate datetime
,HomeTeamID int
,AwayTeamID int
Declare @tvGoals Table (
GoalID int IDENTITY(1,1)
,MatchID int
,PlayerID int
,TeamID int
Declare @tvPlayers Table (
PlayerID int IDENTITY(1,1)
,TeamID int
,PlayerName varchar(30)
Declare @tvTeams Table (
TeamID int IDENTITY(1,1)
,TeamName varchar(20)
Insert @tvTeams
Select 'Winners'
Union All
Select 'Losers'
Union All
Select 'Friars'
Union All
Select 'Planes'
Insert @tvPlayers
Select 1, 'Bill'
Union All
Select 1, 'Jim'
Union All
Select 1, 'Ken'
Union All
Select 2, 'James'
Union All
Select 2, 'Smithy'
Union All
Select 2, 'Flip'
Union All
Select 3, 'Dave'
Union All
Select 3, 'Alan'
Union All
Select 3, 'Ethan'
Union All
Select 4, 'Naomi'
Union All
Select 4, 'Erland'
Union All
Select 4, 'Alejandro'
Insert @tvMatches
Select '20120101', 1, 2
Union All
Select '20120201', 3, 4
Union All
Select '20120301', 4, 1
--Winners beat Losers 3-2
--Planes beat Friars 4-2
--Winners beat Planes 2-1
Insert @tvGoals --Match, Player, Team
Select 1, 1, 1
Union All
Select 1, 3, 1
Union All
Select 1, 5, 2
Union All
Select 1, 6, 2
Union All
Select 1, 2, 1
Union All
Select 2, 7, 3
Union All
Select 2, 8, 3
Union All
Select 2, 10, 4
Union All
Select 2, 11, 4
Union All
Select 2, 12, 4
Union All
Select 2, 11, 4
Union All
Select 3, 1, 1
Union All
Select 3, 3, 1
Union All
Select 3, 11, 4
Using this test data, you want to compile the actual match outcomes.  This can be problematic to do on the fly every time though, if you have a lot of matches or teams to calculate for.  But, with a simple cte, we have:
;with cteMatches as
Select m.MatchID
,m.MatchDate
,m.HomeTeamID
,ht.TeamName HomeTeamName
,m.AwayTeamID
,at.TeamName AwayTeamName
,( Select Count(1)
From @tvGoals g
Where g.MatchID = m.MatchID
And g.TeamID = m.HomeTeamID
) HomeScore
,( Select Count(1)
From @tvGoals g
Where g.MatchID = m.MatchID
And g.TeamID = m.AwayTeamID
) AwayScore
From @tvMatches m
join @tvTeams ht
on m.HomeTeamID = ht.TeamID
join @tvTeams at
on m.AwayTeamID = at.TeamID
) --select * from cteMatches
This returns the MatchID, MatchDate, team information and the score.  Basically, you have the match, team and player data tied to the goals table, so you just do a count (using correlated subqueries) to get the score of each team.  Next step is
to calculate the winner and loser (and eventually whether there even was a winner) by comparing the scores:
,cteWinners as
Select cm.MatchID
,cm.HomeTeamID
,cm.HomeTeamName
,cm.AwayTeamID
,cm.AwayTeamName
,Case
When cm.HomeScore > cm.AwayScore Then cm.HomeTeamID
When cm.HomeScore < cm.AwayScore Then cm.AwayTeamID
Else 0
End WinningTeamID
,Case
When cm.HomeScore > cm.AwayScore Then cm.AwayTeamID
When cm.HomeScore < cm.AwayScore Then cm.HomeTeamID
Else 0
End LosingTeamID
From cteMatches cm
) --select * from ctewinners
This returns MatchID, team information and the ID's for winning and losing teams.  For now it returns 0 if it's a draw.  Once we know the outcomes of all the matches, we calculate the actual win/loss for each team:
,cteRecords as
Select t.TeamName
,Count( Case
When cw.WinningTeamID = t.TeamID Then 1
End
) Wins
,Count( Case
When cw.LosingTeamID = t.TeamID Then 1
End
) Losses
From @tvTeams t
join cteWinners cw
on t.TeamID = cw.HomeTeamID
or t.TeamID = cw.AwayTeamID
Group By t.TeamName
) --select * from cteRecords
That last cte returns just team name, and then the number of wins and losses for each team.  This is where I got stuck with the draws, because I'm not quite sure yet how to properly assign a draw to both teams involved.
Now, finally you put it all together with some simple match to determine the points, and there you are:
Select TeamName
,Wins
,Losses
,(Wins * 3) Points
From cteRecords

Similar Messages

  • Complex sql query

    Hello,
    My question is: I would like to do more complex sql query ( i need to use GROUP BY, HAVING, ORDER BY). Is possible do it with CMP entity bean, or i have to use BMP entity bean or Session bean? Query return about 20-30 items. Can you recommend some design pattern for this situation?
    Thanks in advance
    Daniel H

    Hello,
    My question is: I would like to do more complex sql query ( i need to use GROUP BY, HAVING, ORDER BY). Is possible do it with CMP entity bean, or i have to use BMP entity bean or Session bean? Query return about 20-30 items. Can you recommend some design pattern for this situation?
    Thanks in advance
    Daniel H

  • SQLEception using Complex SQL Query with Java Studio Creator2 Build(060120)

    I am evaluating Java Studio Creator2 for a WEB base application project that will be making SQL queries to an Oracle Database but I have stumble into a problem using complex SQL queries.
    I am getting an SQLException "org.apache.jasper.JasperException: java.lang.RuntimeException: java.sql.SQLException: [sunm][Oracle JDBC Driver][Oracle]ORA-00923: FROM keyword not found where expected". I looks like it cut my sql.
    The SQL that I am trying to execute is
    Select part_name
    from table1, table2
    where table1.part_nbr = table2.part_nbr
    and table2.row_add_dt = (select max(table3.row_add_dt)
    from table3
    where table3.ser_part_id =table2.ser_part_id)
    This is a valid query that it is using 2 different selects to get a part number.
    If posible, point me to the best solution were I will be able to make complex SQL queries like the one above and bigger.
    Is there any way that I can read an SQL query file instead of inserting the SQL query string into the setCommand()?

    I have read that document looking for some anwsers on how to make this kind of query. If I try the query that I have above in the query editor ,the query editor will cut off from the last select that is between ().
    I beleave, there is a work around using the inner joint or outter join command. I will try them to see If I get the corrent result. If not, then I have to keep on asking for possible solutions.
    Anyway, someone in the Creator Team should take a note in adding something like a special criteria in the Add Query Criteria Box for cases like the one I have. The special criteria will be like using another select/from/where to get some result that will be compare.
    Girish, Are you in the Sun Creator Team?

  • SQL or Powershell query to get the SCOM management group id for SCOM 2007 R2 & 2012 / 2012 R2

    Hi All,
    Can any one provide me the SQL or Powershell query to get the SCOM management group id for SCOM 2007 R2 & 2012 / 2012 R2
    I had a SQL query which will query the data from data warehouse and give the management group id but i have lost it for all 3 above.
    Gautam.75801

    Hi Gautam,
    Hope it helps:
    http://blog.tyang.org/2013/03/13/data-aggregation-field-became-empty-in-opsmgr-2007-linked-performance-report/
    http://blog.tyang.org/2012/09/05/mp-authoring-targeting-rms-or-ms/
    Natalya
    ### If my post helped you, please take a moment to Vote as Helpful and\or Mark as an Answer

  • Calculations at query level

    HI Experts,
    I need some calculations at query level,
    find the below user requirement.
    And one more thing we are not authorised to use Customer exits.
    SELECT
    [FA No] As [FA No],
    [FA Description] As [FA Description],
    Sum( CASE WHEN [Posting Date] < @fromDate THEN Amount ELSE 0 END) AS [Starting Balance],
    Sum( CASE WHEN [Posting Date] >= @fromDate AND [Posting Date] <= @toDate  THEN [Debet Amount] ELSE 0 END) AS [Debet Amount],
    Sum( CASE WHEN [Posting Date] >= @fromDate AND [Posting Date] <= @toDate  THEN [Credit Amount] ELSE 0 END) AS [Credit Amount],
    Sum( CASE WHEN [Posting Date] <= @toDate THEN Amount ELSE 0 END) AS [Ending Balance],
    Sum( CASE WHEN [Posting Date] >= @fromDate AND [Posting Date] <= @toDate  THEN [Amount] ELSE 0 END) AS [Net Change]
    FROM FA06data
    GROUP BY [FA No], [FA Description]
    Please help as early as you can.
    Thanks,
    Naveen

    Thanks for your responce.
    we are using Sql with the query designer.
    what we can use? like calculated key figure.

  • ORA-00904 when use column alias in Record Group Query

    Is it possible to use column aliases in Record Group Queries?
    I have a query that runs fine in SQL*Developer, but gives me runtime errors when I use it as a Record Group Query.
    When I use it as a Record Group Query, the Form compiles, but at runtime I receive the following errors:
    FRM-40502: ORACLE error: unable to read list of values
    when I use Help - Display Error, I see:
    ORA-00904:"CHILDNAME":invalid identifier
    The query is something like this
    select decode(complex stuff here) as "childname" ....
    I've tried it with and without the double quotes surrounding the alias name, and have also tried it without using the "as" keyword.
    I would appreciate any suggestions or insights. I'm using Forms 9.0.4.
    Thanks.

    It looks like this is caused by bug 725059:
    "FILTER BEFORE DISPLAY" DOESN'T WORK IF LOV HAS COLUMN ALIASES (TRIAGE1098)
    My LOV does have the Filter Before Display turned on. Here's the text of the bug:
    IF an LOV is created with column aliases in the select statement, (eg: select ename emp_name from emp) and the LOV property "Filter Before Display" is "Yes", THEN when you attempt to filter the LOV at runtime, (eg: type '%' then press the 'Find' button) the internal WHERE clause that forms sends to the database is: WHERE column_alias LIKE '%%' This is incorrect syntax. A client-side sqlnet trace shows this. The correct syntax should be: WHERE column LIKE '%%' . The incorrect syntax results in no rows returned. However no error is displayed by forms to the user.

  • How to change sql expression of SQL-Calculated Attribute of view object ?

    Hi
    jdev 11.1.1.5
    I have a view object with a SQL-Calculated Attribute (sumAnalytic) how can I change sql expression of this attribute in runtime?
    for example in application module method??

    Hi Mr Timo
    Thanks for your reply but I do not need dynamic vo because I can not change all of my vo
    I only need to change expression of SQL-Calculated Attribute of view object in run time.
    For this I set expression in view object something like this 'select 2 from dual' and in run time in my AM method I get the vo query and replace 'select 2 from dual' with something like 'selet sum(amnt) over (partition by 1)' and set new query.
    But I think the better solution must exist
    Thanks

  • Simple sql to mdx query using the max fn

    I'm using the MDX Max fn to get the max of a certain value but now I want get max for a certain pair of values and not all, how could i write this in mdx as a calculation?
    More details: For a certain pair of status and substatus (status=1, substatus=1) from a trans dimension table i want to get the max insertionid (attribute in trans measure table). How would you guys suggest I go about this?
    I'm new to mdx and I'm converting a whole sql statement to a measure not to include it as a named query for performance concerns!
    If needed this is the sql query im converting:
    SELECT TOP (1) InsertionDT
    FROM dbo.TransTasksFFMS_GVT AS TSI
    WHERE (TaskCode = T.TaskCode) AND (TaskStatus = 1) AND (TaskSubStatus = 1)
    ORDER BY InsertionDT) AS RegistrationTimeWithoutConversion
    Another way to think of this is how to apply a certain measure only on certain values and not all values in the browser.

    Hi Junior,
    According to your description, you want to get the max value by using MDX query, right? Since no know your cube detail information, we cannot convert this T-SQL to MDX query. Here is a sample MDX query for your reference. The query below returns the Sale
    Amount measure and the MaxValue calculated member.  The MaxValue calculated member takes the maximum value for members of the Fiscal Year level in the Fiscal hierarchy of the Date dimension.
    WITH
    MEMBER [Measures].[MaxValue] AS
    MAX([Date].[Fiscal].[Fiscal Year].Members, [Measures].[Sales Amount])
    SELECT
    {[Measures].[Sales Amount],[Measures].[MaxValue]} ON COLUMNS,
    {[Date].[Fiscal].[Fiscal Year].Members} ON ROWS
    FROM
    [Adventure Works]
    Reference:Max (MDX)
    Regards,
    Charlie Liao
    TechNet Community Support

  • Easiest way to search for a keyword in over 100 dts packages on a complex SQL 2000 server

    Hi,
    Can anyone tell me the easiest way to search for a keyword (e.g. myfilename.txt) in over 100 dts packages on a complex SQL 2000 server please. I've searched the internet for a solution, and there seem to be various third party tools available, etc. However
    ideally I would like to be able to run a block of code which returns the result within query analyser, since this SQL 2000 server is a production server and I'd rather not have to go through change management for investigation purposes.
    Kind Regards,
    Kieran.
    Kieran Patrick Wood http://www.innovativebusinessintelligence.com http://uk.linkedin.com/in/kieranpatrickwood http://kieranwood.wordpress.com/

    See if this helps
    http://www.sqlservercentral.com/Forums/Topic169278-19-1.aspx
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • The Complex SQL Table Range

    DEAR ALL
    I MAKE SOME SQL TUNING
    AND FOUND THIS
    Problematic SQL Statement
    9 Table operations found in execution plan exceeding the upper limit of
    the Complex SQL Table Range. Full table scan with table size larger than
    the Problematic SQL Full Table Scan Threshold (8
    Kbytes).(TEMPLATE.VPD_SEC_PRIVILEGES 64,
    TEMPLATE.USERS_GROUPS 2048, HRMS.HRMS_ORG_CHART_VPD 128,
    TEMPLATE.VPD_SEC_PRIVILEGES 64, TEMPLATE.USERS_GROUPS 2048)
    BUT I DON'T UNDERSTAND WHAT THAT MEAN
    CAN ANY ONE EXPLAINE THIS?

    Well if this output is from SQL Navigator then I suggest you ask on an SQL Navigator forum what their output means.
    As for tuning "select * from employees" I can tell you it will do a full table scan and performance cannot be improved for such a statement.
    If you're interested in tuning SQL's using Oracle facilities look at this thread...
    When your query takes too long ...

  • SSRS - SQL Server Spatial Query

    Hi, I was hoping someone could help me.
    I'm creating an SSRS report with Map and importing points via SQL Server Spatial query. I have a db table with 8,000 points bu the import only ever brings in the first 2,000 queried (no matter what the filter is). Is there a limitation in SSRS that can be
    changed via a configuration setting?
    Many thanks in advance for any help on this,
    Steve.

    Really appreciate you coming back so quick Olaf.
    No its a straightforward query (select AccountNum, Name, Address, Longitude, Lattitude, UrbanArea, County, MI_STYLE, MI_PRINX, SP_GEOMETRY from <table>)
    Just to give the whole picture. I had 8,000 points in MapInfo version 10. I imported them to SQL Server 2012 via MapInfo Easy Loader.
    The SQL Server spatial points import to SSRS and the Bing overlay map works great (so they import to correct space) but its only a subset of the points that import. I can pick any subset using the WHERE clause but I cannot get all 8,000 points.  
    I was hoping there was a configuration setting somewhere in SSRS that was causing the problem.

  • Conditional SQL in Report Query

    How can I code a conditional SQL in the Report query builder
    to include a WHERE clause parameter or not, depending on the value
    of a report parameter? Basically, what I want to do is:
    select field from table where x=1
    <cfif param.a eq 1>and a=1</cfif>
    Report builder does not like this, but I can't find any help
    on how to do this.

    I don't think CFML tags may be used like that in the SQL of
    report query. But then, I'm not very much into reports. If you're
    just out to get the result, then try
    select field from table
    where
    (x=1 and #param.a# <> 1) or (x=1 and #param.a#=1 and
    a=1)

  • Error [hyt00] [microsoft][odbc sql server driver] query timeout expired

    I have the below network setup:-
    1. Its a simple network at my father's office at a small town called Ichalkaranji (District - Kolhapur, Maharashtra).
    2. We are using private network range 192.168.1.xxx with two Windows Server 2003 Enterprise Edition with SP2 licensed copies and 15 local Windows 7 clients who are only using Server A.
    3. The network is having a TP-Link Braodband Router Connected to internet with the IP 192.168.1.1.
    4. Both there Windows Server 2003 Enterprise Edition with SP2 are running separate SQL Server 2005 Express with Advanced Services, you can treat them as Server A (Problematic Server with IP of 192.168.1.2) 
    and Server B (this is not having any issue with IP of 192.168.1.3).
    5. Server A is also being used by 6 Remote users from our Kolkata office using DDNS facility through the NO IP client software which installed separately on both the servers. Kolkata remote users
    do not use OR access the Server B.
    6. Server B is being used by only 2 Remote users from our Erode office (Under Salem District, Tamilnadu) using DDNS facility through the NO IP client software which installed separately on both
    the servers. Erode remote users do not use OR access the Server A.
    7. The front end application which running separately on both the servers have been developed in VB by a local vendor at Ichalkaranji (District - Kolhapur, Maharashtra).
    8. Both Servers are having the same database structure in terms of design and tables format. Only difference is that both the servers are being used separately.
    9. This error OR problem is only related to Server A, where on the clients we get the message "error [hyt00] [microsoft][odbc sql server driver] query timeout expired" every now and then.
    10. We have to frequently reboot the server whenever we get this message on the client machines. May be after rebooting every thing works perfectly for 2 hours / 5 Hours / may be one full day but
    the the error will come back for sure.
    11. Current Database back up size on Server A is around 35 GB and take around 1 hour 15 minutes daily to take the back up.
    12. Current Database back up size on Server B is around 3 GB and take around 5 to 10 minutes daily to take the back up.
    13. One thing I have noticed is that when ever we reboot Server A, for some time sqlsrvr.exe file will show memory usage of 200 to 300 MBs but it will start using slowly, what i understand is that
    this is the way SQL Server works.
    14. Both the Servers are also running Quick heal Antivirus Server Edition separate licensed copies also.
    15. Server B is also running Tally ERP 9 Licenses copy which is being used locally by 15 users of Ichalkaranji (District - Kolhapur, Maharashtra) same users
    Can any one help to resolve this issue. Any help will be highly appreciated.

    The error message "query timeout expired" occurs, because by default many APIs, including ODBC only waits for 30 seconds for SQL Server to send any output. If no data has been seen for this period of time, they tell SQL Server to cancel execution
    and return this error to the caller.
    This timeout could be seen as a token that the query is taking too long time to execute and this needs to be fixed. But it can also be a pain in the rear parts, if you are content with a report taking five minutes, because you only run it once a day.
    The simplest way to get rid of the error is to set the timeout to zero, which means "wait forever". This is something your vendor would have to do. This may, however, not resolve the problem, as the users may just find that the application is hanging.
    To wit, there are two reasons why the query takes more than 30 seconds to complete. One is that there is simply that much work to do. This can be reduced by adding indexes or by doing other tuning, if the execution time is not acceptable. The other possibility
    is blocking. That is, there is a process blocking this query from completing. This is much more likely to require attention.
    It is not clear to me, whether the vendor has developed the database part as well. In this case, you should probably call the vendor's support desk to have them to sort this out.
    Finally, I am little puzzled. You say that you are using Express Edition, but one of the databases is 35 GB in size. 35 GB is far above the limit for Express Edition.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to create Infoset&user group query--(query report)

    Hi Guys,
      how to create Infoset&user group query--(query report),
      Pls send me the exact procedure with Example....
                                                                              Regards:
                                                                              Kumar .G

    goto SQ03 and create an User Group If U want to create Ur Own.
    Goto SQ02 to create Ur Infoset by Giving Logical database name or Simple Database table
    Then Choose What ever data U need to be included in The Qurey in field Groups.
    Then Generate the Infoset
    Now Assign the infoset to user group
    Now goto SQ01 and Click on Other user group Button and choose Ur user Group.
    Then in the USer group select Ur Infoset and then create Ur own Query and save this.
    Now select the infoset query and goto More functions under Query menu and Generate report name.
    Now Create a transaction code for the report name generated.
    Now use the Tcode.
    Hope U have got the basic idea of creating Queries.
    ~BiSu

  • BAM Data Control - Group query with Active Data Service

    Trying to get a group query from a BAM data control to work with Active Data Service in an ADF application (JDeveloper 11.1.1.4.0).
    With a flat query, as the data changes, I can see DataChangeEvents fired, resulting in a data push to the client -
    <BAMDataChangeEventFilter> <log>
    #### DataChangeEvent #### on [DataControl name=CEP_Person_DOB_Flat, binding=data.view_mainPageDef.FlatDOB1.view_pageDefs_FlatDOBViewPageDef_WEB_INF_FlatDOB_xml_FlatDOB.QueryIterator]
    Filter/Collection Id : 1966
    Collection Level : 0
    Event Id : 5
    ==== DataChangeEntry (#1)
    ChangeType : INSERT_AFTER
    KeyPath : [2157, 0]
    InsertKeyPath : [null, 0]
    AttributeNames : [id, _PersonKey, _County, _Surname, _AGE, _DOB, _Country, _FirstName]
    AttributeValues : [2157, 10008/129, Vagzukarbsm, Gnnfzxxyqfgpsijcr, 110, Thu Dec 26 00:00:00 GMT 1901, Ekcqvrkoksr, Vwhm]
    When I try a group query on the same data, currently just trying to group by _DOB for every 10 years to count the number of people, I get no data change events fired, so don't get any data pushed to the client, though the data has been changed if I refresh the page.
    Any ideas ?

    can you include bam and jdev versions and also include exception from logs?

Maybe you are looking for