# Group by

### Output odd and even numbers

### Run full text search on Shakespeare and group results by speaker

    xquery version "3.0";

    let $query := "king"
    for $speechBySpeaker in //SPEECH[ft:query(., $query)]
    group by $speaker := $speechBySpeaker/SPEAKER
    order by $speaker
    return
        <speaker name="{$speaker}">
        { $speechBySpeaker }
        </speaker>

### Group results by speaker and scene

    xquery version "3.0";

    let $query := "poison"
    for $speechBySpeaker in //SPEECH[ft:query(., $query)]
    group by $speaker := $speechBySpeaker/SPEAKER
    order by $speaker
    return
        <ul>
            <li>
                <h3>{$speaker/text()}</h3>
                <ul>
                {
                    for $speech in $speechBySpeaker
                    group by $scene := $speech/ancestor::SCENE/TITLE
                    return
                        <li>
                            <h4>{$scene/text()}</h4>
                            <ul>
                            {
                                for $line in util:expand($speech)/LINE[exist:match]
                                return
                                    <li>
                                    {
                                        for $node in $line/node()
                                        return
                                            typeswitch($node)
                                                case element(exist:match) return
                                                    <mark>{$node/text()}</mark>
                                                default return
                                                    $node
                                    }
                                    </li>
                            }
                            </ul>
                        </li>
                }
                </ul>
            </li>
        </ul>