4

I have a table of golf match-ups taken from Betfair's downloadable CSV files of historical data. They look like this:

event         selection
S. Garcia     Garcia
S. Garcia     Woods
P. Mickelson  Mickelson
P. Mickelson  Donald
E. Els        McIlroy
E. Els        Els

I need a query that provides the following output:

event         selection_a  selection_b
S. Garcia     Garcia       Woods
S. Garcia     Woods        Garcia
P. Mickelson  Mickelson    Donald
P. Mickelson  Donald       Mickelson
E. Els        McIlroy      Els
E. Els        Els          McIlroy

To conclude, the event name is just one of the players in the match-up. Within each match up there will be two players, how do I write a query that recognises that Garcia played Woods, Mickelson played Donald and Els played McIlroy?

Help! :-)

4

2 に答える 2

5
SELECT
    g.event,
    Min(g.selection) AS selection_a,
    Max(g.selection) AS selection_b
FROM Golf_matches AS g
GROUP BY g.event
UNION ALL
SELECT
    g.event,
    Max(g.selection),
    Min(g.selection)
FROM Golf_matches AS g
GROUP BY g.event
ORDER BY 1, 2;
于 2012-06-27T13:42:16.373 に答える
3

SQL Ninjaが登場し、このアプローチがいかに悪いかを指摘することは間違いありませんが、私はそれをいじってみました。私がこれまでに行ったアプローチは次のとおりです(私の宣言が含まれていますが、あなたの場合はそれを無視して@Matchをテーブル名に置き換えてください)

DECLARE @Match TABLE (
    eventName NVARCHAR(MAX),
    selection NVARCHAR(MAX)
)

INSERT INTO @Match(eventName, selection)
VALUES ('S. Garcia', 'Garcia'),
       ('S. Garcia', 'Woods'),
       ('P. Mickelson', 'Mickelson'),
       ('P. Mickelson', 'Donald'),
       ('E. Els', 'McIlroy'),
       ('E. Els', 'Els')

SELECT M1.eventName, M1.selection AS SelectionA, M2.selection AS SelectionB 
    FROM @Match M1 
        INNER JOIN @Match M2 
          ON M1.eventName = M2.eventName
WHERE M1.selection <> M2.selection
于 2012-06-27T13:09:03.483 に答える