<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Elif Pulukcu on Medium]]></title>
        <description><![CDATA[Stories by Elif Pulukcu on Medium]]></description>
        <link>https://medium.com/@elifpulukcu?source=rss-6eb8b0dda6cf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-QCCXPRm5MuceEtJpugN4w.jpeg</url>
            <title>Stories by Elif Pulukcu on Medium</title>
            <link>https://medium.com/@elifpulukcu?source=rss-6eb8b0dda6cf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:50:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elifpulukcu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building an A* Pathfinding Application for Istanbul’s Rail Network]]></title>
            <link>https://medium.com/@elifpulukcu/building-an-a-pathfinding-application-for-istanbuls-rail-network-fb9620a66167?source=rss-6eb8b0dda6cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb9620a66167</guid>
            <category><![CDATA[route-optimization]]></category>
            <category><![CDATA[astar]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Elif Pulukcu]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 08:29:37 GMT</pubDate>
            <atom:updated>2025-03-05T03:27:47.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*q54qXNq4frd9_MsoWZJJRQ.jpeg" /><figcaption>“Relativity” (1953) by M.C. Escher — This iconic lithograph illustrates a complex, multi-directional architectural world, symbolizing the intricate and interconnected nature of systems. Its surreal and paradoxical design resonates with the complexity of urban networks, like Istanbul’s railways.</figcaption></figure><h3>Introduction</h3><p>Istanbul’s rail system is continually expanding, making it both fascinating and challenging to develop reliable route planners. As new lines such as M11 (Gayrettepe–Istanbul Airport) come into service, official open data sources often lag behind in reflecting these expansions. While exploring the Istanbul Metropolitan Municipality (İBB) Open Data Portal, I noticed that many developers could not integrate these newer lines simply because the datasets were outdated. To address this gap, I built my own route planner leveraging the most recent <a href="https://data.ibb.gov.tr/en/dataset/rayli-sistem-istasyon-noktalari-verisi/resource/3dc8203f-3613-48a8-85e9-24fffb7821ad?view_id=32d900ee-7ed4-4ed2-a4a6-be53ab1fc02e">GeoJSON data</a> I could find, adding transfer information manually where necessary. This article will walk you through the project’s design, how the A* pathfinding algorithm powers route calculations, and the challenges of working with incomplete or evolving data sources.</p><p>This project’s source code is publicly available on <a href="https://github.com/elifpulukcu/Istanbul-railway-itinerary">my GitHub repository</a>. If you require the JSON file containing transfer rules, feel free to reach out. A video demonstration of the project is also accessible through <a href="https://drive.google.com/file/d/1Yn46T1qA9aPNmqeLEwgGaMpTx37p_nQV/view?usp=share_link">this link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i25yaKPJtWxa0HLhouc6ow.png" /></figure><h3>Data Structures and Core Concepts</h3><h4>Graph Representation</h4><p>All stations are stored in a JSON file (stations.json), where each feature entry defines:</p><ul><li><strong>Station name (</strong><strong>ISTASYON)</strong></li><li><strong>Line name (</strong><strong>PROJE_ADI)</strong></li><li><strong>Coordinates (longitude &amp; latitude)</strong></li></ul><p>A station’s adjacency (i.e., which stations are accessible from a given station) is inferred primarily by line continuity and explicit transfer rules. The code below demonstrates how the graph is constructed:</p><pre>@staticmethod<br>def create_station_graph(features: List[Dict]) -&gt; Dict:<br>    graph: Dict[str, Dict] = {}<br><br>    # Create an empty graph node for each station<br>    for f in features:<br>        st_name = f[&#39;properties&#39;][&#39;ISTASYON&#39;]<br>        line_name = f[&#39;properties&#39;][&#39;PROJE_ADI&#39;]<br>        coords = f[&#39;geometry&#39;][&#39;coordinates&#39;]<br><br>        if st_name not in graph:<br>            graph[st_name] = {<br>                &#39;coords&#39;: coords,<br>                &#39;lines&#39;: set([line_name]),<br>                &#39;connections&#39;: []<br>            }<br>        else:<br>            graph[st_name][&#39;lines&#39;].add(line_name)<br><br>    # Sort stations by &#39;order&#39; property within each line<br>    stations_by_line = defaultdict(list)<br>    for f in features:<br>        line = f[&#39;properties&#39;][&#39;PROJE_ADI&#39;]<br>        st_name = f[&#39;properties&#39;][&#39;ISTASYON&#39;]<br>        order_val = f[&#39;properties&#39;].get(&#39;order&#39;, 9999)<br>        stations_by_line[line].append((st_name, order_val))<br><br>    for line, st_list in stations_by_line.items():<br>        st_list.sort(key=lambda x: x[1])<br>        # Connect consecutive stations along the line<br>        for i in range(len(st_list) - 1):<br>            stationA = st_list[i][0]<br>            stationB = st_list[i+1][0]<br>            graph[stationA][&#39;connections&#39;].append((stationB, line))<br>            graph[stationB][&#39;connections&#39;].append((stationA, line))<br><br>    # Apply transfer rules between stations<br>    transfers = load_transfer_rules()<br>    for rule in transfers:<br>        stA, lineA = rule[&#39;stationA&#39;], rule[&#39;lineA&#39;]<br>        stB, lineB = rule[&#39;stationB&#39;], rule[&#39;lineB&#39;]<br><br>        if stA in graph and stB in graph:<br>            graph[stA][&#39;connections&#39;].append((stB, lineB))<br>            graph[stB][&#39;connections&#39;].append((stA, lineA))<br><br>    return graph</pre><p>Each graph[station_name] entry is a dictionary containing:</p><ul><li>coords: The (longitude, latitude) coordinates for the station.</li><li>lines: The set of lines that serve this station.</li><li>connections: A list of (other_station, line_name) tuples, representing all directly connected stations.</li></ul><h4>Transfer Rules</h4><p>Some stations serve multiple lines, enabling passengers to switch lines without leaving the station. To reflect these interchange points correctly, a <strong>transfer rules</strong> JSON file (transfer_rules.json) is referenced. Each rule clarifies which station and line pairs constitute valid transfers. The TransferCache class manages these rules:</p><pre>class TransferCache:<br>    def __init__(self, transfer_rules: List[Dict]):<br>        self._cache = set()<br>        for rule in transfer_rules:<br>            self._cache.add((<br>                rule[&#39;stationA&#39;], rule[&#39;lineA&#39;],<br>                rule[&#39;stationB&#39;], rule[&#39;lineB&#39;]<br>            ))<br>            self._cache.add((<br>                rule[&#39;stationB&#39;], rule[&#39;lineB&#39;],<br>                rule[&#39;stationA&#39;], rule[&#39;lineA&#39;]<br>            ))<br><br>    def is_valid_transfer(self, stA: str, lineA: str, stB: str, lineB: str) -&gt; bool:<br>        if lineA == lineB:<br>            return True<br>        return (stA, lineA, stB, lineB) in self._cache</pre><p>The method is_valid_transfer(...) checks whether moving from one station-line pair to another station-line pair is legal. If lines differ, it validates against the cache of known transfers.</p><h3>A* Search Algorithm</h3><h4><strong>Mathematical Underpinnings</strong></h4><p>A* relies on two core components for each node (in this context, each “node” is a (station, line) pair):</p><ol><li><strong>g(n)</strong>: The cost of the path from the start node to the current node nn.</li><li><strong>h(n)</strong>: The heuristic estimate of the remaining distance to the goal.</li></ol><p>The total estimated cost f(n) is: f(n) = g(n) + h(n)</p><p>Using this approach, the algorithm expands the node with the smallest f(n) at each iteration, ensuring a path that is either optimal or near-optimal, assuming the heuristic is admissible and consistent.</p><h4><strong>Calculating the Heuristic</strong></h4><p>A Euclidean (or more precisely, Haversine-based) distance function is employed as the heuristic to estimate remaining distance. The function below computes the geodesic distance in kilometers between two coordinates:</p><pre>def calculate_distance(coord1: Tuple[float, float], coord2: Tuple[float, float]) -&gt; float:<br>    lon1, lat1 = coord1<br>    lon2, lat2 = coord2<br>    <br>    R = 6371.0  # Earth&#39;s radius in km<br>    lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])<br>    dlat = lat2 - lat1<br>    dlon = lon2 - lon1<br>    a = math.sin(dlat/2)**2 + math.cos(lat1)*math.cos(lat2)*math.sin(dlon/2)**2<br>    c = 2 * math.asin(math.sqrt(a))<br>    return R * c<br><br>def calculate_heuristic(graph: Dict, current: str, goal: str) -&gt; float:<br>    coord1 = graph[current][&#39;coords&#39;]<br>    coord2 = graph[goal][&#39;coords&#39;]<br>    return calculate_distance(coord1, coord2)</pre><p>Given that a station has coordinates (lat, lng), the distance to the goal station is a realistic measure of &quot;cost to go.&quot;</p><h4><strong>Open and Closed Sets</strong></h4><p>In A*, two sets (or lists) typically manage the exploration of the search space:</p><ul><li><strong>Open set</strong>: Nodes to be evaluated.</li><li><strong>Closed set</strong>: Nodes already evaluated.</li></ul><p>Here, these sets are maintained by a custom PriorityQueue (for the open set) and a Python set (for the closed set, referred to as explored). The PriorityQueue class is defined to support priority-based insertion and retrieval:</p><pre>class PriorityQueue:<br>    def __init__(self):<br>        self._queue = []<br>        self._entry_finder = {}<br>        self._counter = 0<br>        self._REMOVED = &#39;&lt;removed&gt;&#39;<br>        <br>    def empty(self) -&gt; bool:<br>        return not self._entry_finder<br><br>    def put(self, item: Tuple[str, str], priority: float) -&gt; None:<br>        if item in self._entry_finder:<br>            self.remove(item)<br>        entry = [priority, self._counter, item]<br>        self._entry_finder[item] = entry<br>        heapq.heappush(self._queue, entry)<br>        self._counter += 1<br><br>    def remove(self, item: Tuple[str, str]) -&gt; None:<br>        entry = self._entry_finder.pop(item)<br>        entry[-1] = self._REMOVED<br><br>    def get(self) -&gt; Tuple[str, str]:<br>        while self._queue:<br>            priority, count, item = heapq.heappop(self._queue)<br>            if item is not self._REMOVED:<br>                del self._entry_finder[item]<br>                return item<br>        raise KeyError(&#39;get from empty priority queue&#39;)</pre><h4><strong>Path-Finding with A* (Function by Function)</strong></h4><p>The main pathfinding logic lives in the `AStarPathfinder` class.</p><p><strong>Initialization</strong><br>The constructor receives the station graph and a TransferCache instance:</p><pre>class AStarPathfinder:<br>    def __init__(self, graph: Dict, transfer_cache: TransferCache):<br>        self.graph = graph<br>        self.transfer_cache = transfer_cache<br>        self.frontier = PriorityQueue()<br>        self.g_scores: Dict[Tuple[str, str], float] = {}<br>        self.came_from: Dict[Tuple[str, str], Optional[Tuple[str, str]]] = {}<br>        self.transfer_counts: Dict[Tuple[str, str], int] = {}</pre><p><strong>Cost Calculation</strong><br>The _calculate_cost(...) method adds a penalty when switching lines, reflecting transfer inconvenience:</p><pre>def _calculate_cost(self, current_station: str, current_line: str, <br>                    next_station: str, next_line: str) -&gt; float:<br>    dist = calculate_distance(<br>        self.graph[current_station][&#39;coords&#39;],<br>        self.graph[next_station][&#39;coords&#39;]<br>    )<br>    if current_line != next_line:<br>        # Additional cost for transfers<br>        return dist * TRANSFER_COST + TRANSFER_DISTANCE_PENALTY<br>    return dist</pre><p>In this project, TRANSFER_COST and TRANSFER_DISTANCE_PENALTY are constants tuned to reflect real-world annoyance/delay from line changes.</p><p><strong>Main Search Entry Point </strong><br>The find_path(...) method initializes g_scores (cost so far), estimates a heuristic for each possible start-state combination, and iterates until the goal is found or the open set is empty:</p><pre>def find_path(self, start: str, goal: str, <br>              end_line: Optional[str] = None<br>              ) -&gt; Tuple[Optional[List[str]], Optional[List[str]], <br>                         Optional[float], Optional[int]]:<br>    if start not in self.graph or goal not in self.graph:<br>        return None, None, None, None<br><br>    self.frontier = PriorityQueue()<br>    self.g_scores.clear()<br>    self.came_from.clear()<br>    self.transfer_counts.clear()<br>    explored: Set[Tuple[str, str]] = set()<br><br>    # Each station can be served by multiple lines, <br>    # so treat each (station, line) as a possible start<br>    for start_line in self.graph[start][&#39;lines&#39;]:<br>        start_state = (start, start_line)<br>        self.g_scores[start_state] = 0.0<br>        self.came_from[start_state] = None<br>        self.transfer_counts[start_state] = 0<br>        h_score = calculate_heuristic(self.graph, start, goal)<br>        self.frontier.put(start_state, h_score)<br><br>    final_state = None<br><br>    # A* iteration<br>    while not self.frontier.empty():<br>        current_state = self.frontier.get()<br>        current_station, current_line = current_state<br><br>        # Check if goal is reached<br>        if current_station == goal:<br>            if end_line is None or current_line == end_line:<br>                final_state = current_state<br>                break<br><br>        if current_state in explored:<br>            continue<br>        explored.add(current_state)<br><br>        # Explore neighbors<br>        for next_station, next_line in self.graph[current_station][&#39;connections&#39;]:<br>            if not self.transfer_cache.is_valid_transfer(<br>                current_station, current_line,<br>                next_station, next_line<br>            ):<br>                continue<br><br>            next_state = (next_station, next_line)<br>            if next_state in explored:<br>                continue<br><br>            cost = self._calculate_cost(current_station, current_line,<br>                                         next_station, next_line)<br>            tentative_g = self.g_scores[current_state] + cost<br><br>            if (next_state not in self.g_scores or <br>                tentative_g &lt; self.g_scores[next_state]):<br>                self.g_scores[next_state] = tentative_g<br>                self.came_from[next_state] = current_state<br>                self.transfer_counts[next_state] = (<br>                    self.transfer_counts[current_state] + <br>                    (1 if current_line != next_line else 0)<br>                )<br>                h_score = calculate_heuristic(self.graph, next_station, goal)<br>                f_score = tentative_g + h_score<br>                self.frontier.put(next_state, f_score)<br><br>    if not final_state:<br>        return None, None, None, None<br><br>    path = self._reconstruct_path(final_state)<br>    stations = [s for (s, _) in path]<br>    details = _create_path_details(path)<br>    distance = self.g_scores[final_state]<br>    transfers = self.transfer_counts[final_state]<br><br>    return stations, details, distance, transfers</pre><p><strong>Path Reconstruction </strong><br>Once the goal is found, _reconstruct_path(...) traces back through came_from to build the complete route:</p><pre>def _reconstruct_path(self, final_state: Tuple[str, str]) -&gt; List[Tuple[str, str]]:<br>    path = []<br>    current = final_state<br>    while current:<br>        path.append(current)<br>        current = self.came_from[current]<br>    return list(reversed(path))</pre><p><strong>Generating Route Details </strong><br>The _create_path_details(...) function produces a readable list of steps (including transfer points) to display to users:</p><pre>def _create_path_details(path_tuples: List[Tuple[str, str]]) -&gt; List[str]:<br>    details = []<br>    start_station, start_line = path_tuples[0]<br>    details.append(f&quot;🏁 &lt;b&gt;Start:&lt;/b&gt; {start_station} ({start_line})&quot;)<br><br>    for i in range(1, len(path_tuples)):<br>        current_station, current_line = path_tuples[i]<br>        prev_station, prev_line = path_tuples[i-1]<br>        if current_line != prev_line:<br>            details.append(f&quot;Transfer at {current_station}:&quot;)<br>            details.append(f&quot;&lt;b&gt;  • From: &lt;/b&gt; {prev_line}&quot;)<br>            details.append(f&quot;&lt;b&gt;  • To: &lt;/b&gt; {current_line}&quot;)<br><br>    end_station, end_line = path_tuples[-1]<br>    details.append(f&quot;&lt;b&gt;Destination:&lt;/b&gt; {end_station} ({end_line})&quot;)<br><br>    return details</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UlWn5n4pSaSPN_lseA23A.png" /></figure><h3>Backend Implementation with Flask</h3><p>The Flask backend (app.py) handles requests for:</p><ol><li><strong>Station Data</strong> (/data/stations.json)</li><li><strong>Search Queries</strong> (/api/search_stations)</li><li><strong>Route Calculation</strong> (/api/find_route)</li></ol><p>The route calculation endpoint is responsible for creating the graph and TransferCache, instantiating the AStarPathfinder, and returning the path, distance, and transfers as JSON:</p><pre>@app.route(&#39;/api/find_route&#39;)<br>def api_find_route():<br>    start = request.args.get(&#39;start&#39;)<br>    end = request.args.get(&#39;end&#39;)<br>    end_line = request.args.get(&#39;end_line&#39;)<br><br>    if not start or not end:<br>        return jsonify({&quot;error&quot;: &quot;Missing start or end station&quot;}), 400<br><br>    features = load_stations()<br>    transfer_cache = TransferCache(load_transfer_rules())<br>    graph = transfer_cache.create_station_graph(features)<br>    <br>    pathfinder = AStarPathfinder(graph, transfer_cache)<br>    path, details, distance, transfers = pathfinder.find_path(start, end, end_line)<br><br>    if not path:<br>        return jsonify({&quot;error&quot;: &quot;No route found&quot;}), 404<br><br>    response_data = {<br>        &quot;path&quot;: path,<br>        &quot;details&quot;: details,<br>        &quot;distance&quot;: distance,<br>        &quot;transfers&quot;: transfers<br>    }<br>    return jsonify(response_data)</pre><h3>Frontend: User Interface and Experience</h3><h4>Leaflet Map</h4><p>The interface builds on <strong>Leaflet</strong> to render an interactive map. A tile layer from Carto is set as a backdrop, and stations are added via L.circleMarker objects:</p><pre>const map = L.map(&#39;map&#39;).setView([41.0082, 28.9784], 11);<br>L.tileLayer(&#39;https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png&#39;, {<br>    maxZoom: 19,<br>    attribution: &#39;© OpenStreetMap contributors&#39;<br>}).addTo(map);</pre><p>Each line is rendered using a polyline in its specific color. Stations are drawn as circle markers with on-hover events for highlighting.</p><h4>Searching for Stations</h4><p>Two search boxes (start-station and end-station) prompt users to enter the desired start and end stations. JavaScript sends a query to /api/search_stations and populates a dropdown with matching results.</p><pre>async function searchStations(query) {<br>    if (query.length &lt; 2) return [];<br>    const response = await fetch(`/api/search_stations?query=${encodeURIComponent(query)}`);<br>    return await response.json();<br>}</pre><p>Selecting a station from the dropdown updates selectedStart or selectedEnd, enabling the <strong>Find Route</strong> button.</p><h4>Calculating the Route</h4><p>Clicking the <strong>Find Route</strong> button triggers a call to the Flask route-finding API:</p><pre>async function findRoute() {<br>    if (!selectedStart || !selectedEnd) return;<br><br>    const resp = await fetch(<br>        `/api/find_route?start=${encodeURIComponent(selectedStart.station)}` +<br>        `&amp;end=${encodeURIComponent(selectedEnd.station)}` +<br>        `&amp;end_line=${encodeURIComponent(selectedEnd.line)}`<br>    );<br>    const data = await resp.json();<br><br>    // Display route details in the UI, highlight path on the map, etc.<br>}</pre><h4>Animating the Route</h4><p>To enhance user experience, stations along the route are animated sequentially:</p><pre>async function animateRouteOnMap(coords) {<br>    if (!coords || coords.length &lt; 2) return;<br><br>    const marker = L.circleMarker(coords[0], {<br>        radius: 8,<br>        fillColor: &#39;#FF4081&#39;,<br>        color: &#39;#FF4081&#39;,<br>        weight: 2,<br>        opacity: 1,<br>        fillOpacity: 0.8,<br>    }).addTo(map); <br><br>    let currentIndex = 0;<br>    const animationSpeed = 500; <br><br>    const interval = setInterval(() =&gt; {<br>        currentIndex++;<br>        if (currentIndex &gt;= coords.length) {<br>            clearInterval(interval);<br>            map.removeLayer(marker);<br>            return;<br>        }<br>        marker.setLatLng(coords[currentIndex]);<br>    }, animationSpeed);<br>}</pre><p>This adds an engaging layer of interactivity, showing how the algorithm “traverses” the track between stations.</p><h4>Legend and Line Colors</h4><p>A legend is displayed in the bottom-right corner. Lines are grouped by type (Metro, Tram, Funicular, Cable Car, Suburban) and color-coded for easy recognition. Clicking the legend’s header toggles its visibility, preventing clutter.</p><h3><strong>Conclusion</strong></h3><p>An A*-based route planning system effectively handles Istanbul’s complex railway network. By modeling each station as a node (or, more precisely, (station, line) pairs) and incorporating realistic transfer costs, the algorithm yields practical routes.</p><ul><li><strong>A* Algorithm</strong> with a Haversine distance heuristic for accurate path estimation.</li><li><strong>Line and Transfer Modeling</strong> supporting multi-line stations and explicit interchange rules.</li><li><strong>Leaflet UI</strong> for an intuitive, map-based experience with real-time station search and route animations.</li></ul><p>The end result is a cohesive application that provides fast, user-friendly navigation. The technical details covered here provide a reference for building route-finding solutions in similarly large and complex transit networks.</p><h4>Further Reading &amp; Resources</h4><ul><li><a href="https://data.ibb.gov.tr/">Official İBB Open Data Portal</a> (İstanbul Büyükşehir Belediyesi)</li><li><a href="http://theory.stanford.edu/~amitp/GameProgramming/">A* Pathfinding Algorithm Explanation by Stanford CS</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc7946">GeoJSON Specification</a></li></ul><p>Thank you for reading! If you have questions or want to collaborate on this project, please leave a comment or reach out via GitHub.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb9620a66167" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Advanced SQL Functions in BigQuery with the NYC Taxi Trips Dataset]]></title>
            <link>https://blog.dataengineerthings.org/exploring-advanced-sql-functions-in-bigquery-with-the-nyc-taxi-trips-dataset-0067f94ccab8?source=rss-6eb8b0dda6cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0067f94ccab8</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[advanced-sql]]></category>
            <dc:creator><![CDATA[Elif Pulukcu]]></dc:creator>
            <pubDate>Wed, 25 Dec 2024 10:17:41 GMT</pubDate>
            <atom:updated>2024-12-30T16:04:04.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*k1HT3KaV6JaVg3Jj-DgKlQ.png" /><figcaption>“The Barbarians” (1937), Max Ernst, The Metropolitan Museum of Art</figcaption></figure><p>Advanced SQL functions play a crucial role in deriving richer insights and handling complex analytical tasks. While basic aggregations and simple joins may suffice for introductory projects, techniques such as window functions (for running totals or rankings), common table expressions (for organizing multi-step logic), and conditional aggregations enable a deeper level of data exploration and more efficient query designs.</p><p>This article applies these methods to the <strong>NYC Taxi Trips dataset</strong> in <strong>Google BigQuery</strong>, covering a variety of use cases:</p><ul><li><strong>Outlier detection</strong> with statistical boundaries, leveraging 3-sigma rules to flag potential anomalies.</li><li><strong>Self-joins</strong> that track consecutive events or trips, such as monitoring how vehicles or bikes move from one location to another within short intervals.</li><li><strong>Window functions</strong> like RANK, LAG, LEAD, and framing clauses (ROWS BETWEEN, RANGE BETWEEN) to handle cumulative sums, moving averages, and top-N analyses.</li><li><strong>CTEs</strong> for cleaner query structure, breaking down complex transformations into logical parts and ensuring code remains maintainable.</li><li><strong>Creating and managing permanent tables</strong> to store snapshots of data (e.g., outlier thresholds or aggregated statistics), reducing computational overhead on subsequent queries.</li><li><strong>Maintenance scheduling</strong> queries, relying on distance tracking and thresholds to identify when specific bikes or vehicles require service.</li></ul><p>By the end of this walkthrough, you will have hands-on experience applying these advanced functions to uncover meaningful insights, optimize performance, and streamline your workflow in BigQuery. Let’s get started!</p><h3>A Quick Glance at the Dataset</h3><p>Before diving into advanced SQL techniques, it’s vital to understand the structure of our data. In this example, each row represents a taxi trip with fields like vendor_id, pickup_datetime, dropoff_datetime, and fare-related details (fare_amount, tip_amount, total_amount). By reviewing the schema, we can confirm which columns and data types we&#39;ll be working with and ensure that our queries align with the dataset&#39;s layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*liI5NkFA3szOHb1E2oyzkw.png" /></figure><p>By reviewing the schema, we can confirm which columns and data types we’ll be working with and ensure that our queries align with the dataset’s layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*hKbL_Yehtoeaa_mtKgOOYA.png" /></figure><h3>Exploring a Sample of the Data</h3><p>In this query, we use LIMIT 10 to return only the first ten rows from the tlc_yellow_trips_2022 table. This approach — sometimes referred to as looking at the <strong>row source</strong> — lets us quickly inspect a small portion of the dataset for an initial sanity check, without having to scan the entire table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0ATD_Gk3zxSi9p7wbnQ4A.png" /></figure><p>When you project specific columns (e.g., rate_code, store_and_fwd_flag), you explicitly select only those fields, reducing the data scanned and focusing on what you need. Conversely, using EXCEPT(…) returns every column except the ones you exclude. This is especially handy if you want to inspect most of the table but skip certain fields. Both approaches help control data usage and costs in BigQuery, where you pay based on the amount of data processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpDaIr1n32zu3B-dw15f-A.png" /></figure><h3>Renaming Columns and Simple Transformations</h3><p>One of the easiest ways to make your queries more readable is by assigning column aliases with the AS keyword — here, pickup_datetime becomes pickup_dt and dropoff_datetime becomes dropoff_dt. You can also perform simple arithmetic operations directly in your SELECT statement, such as (total_amount + tip_amount) AS grand_total. These small transformations help you quickly consolidate important values and keep your queries both clear and concise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dxz3gbn9BgcFwgqfeRN0IA.png" /></figure><h3>Conditional Logic with CASE</h3><p>In this query, we use the CASE expression to categorize rows based on the value of passenger_count. For example, if passenger_count equals 1, we label it as &#39;one&#39;; if it equals 2, we label it as &#39;two&#39;; otherwise, we label it as &#39;more&#39;. This approach allows you to define multiple conditional branches in a single expression and derive new, descriptive fields without needing separate queries or more complex logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMl-gUZeaFqu9poyYFGZqg.png" /></figure><h3>Alternate Syntax for CASE Expressions</h3><p>Here, we use the CASE &lt;column&gt; WHEN &lt;value&gt; THEN structure, which allows a more concise way to check for direct equality — such as WHEN 1 THEN &#39;one&#39;. In contrast, the CASE WHEN &lt;condition&gt; THEN form is more versatile, letting you use broader comparisons (e.g., WHEN passenger_count &gt; 2 THEN &#39;many&#39;). Both syntaxes achieve similar results for equality checks, but the first is shorter when you only need to match specific values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5rasSghHlPt3ot_XRIoFg.png" /></figure><h3>Conditional Logic for Dynamic Calculations</h3><p>The CASE expression in this query demonstrates how you can apply different arithmetic operations depending on a boolean condition. Unlike the simpler CASE &lt;column&gt; WHEN &lt;value&gt; THEN form, each WHEN clause here uses a more flexible boolean expression (e.g., trip_distance &lt; 3). The logic is straightforward:</p><ul><li>If the trip_distance is less than 3, the total_amount is multiplied by 1.5.</li><li>For trips of distance between 3 and 10 (inclusive), the total_amount remains unchanged.</li><li>Otherwise, the amount is reduced to 90% of its original value (total_amount * 0.9).</li></ul><p>This technique helps you write concise yet powerful conditional calculations in a single query — ideal for creating on-the-fly pricing adjustments or category assignments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfngK5mBBiNpYIVZsucwYQ.png" /></figure><h3>Streamlined Range Checks with BETWEEN</h3><p>Here, we’ve replaced the explicit trip_distance &lt;= 10 AND trip_distance &gt;= 3 condition with the more concise BETWEEN 3 AND 10. Functionally, both forms achieve the same result:</p><ul><li>If the trip_distance is less than 3, the total_amount is multiplied by 1.5.</li><li>If it’s BETWEEN 3 AND 10 (inclusive), the total_amount remains unchanged.</li><li>Otherwise, it’s multiplied by 0.9.</li></ul><p>The BETWEEN keyword simply makes the range condition more readable and compact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYzcAoA1gTPqXra_WFv1dQ.png" /></figure><h3>Filtering with the WHERE Clause and SQL’s Three-Valued Logic</h3><p>A fundamental part of SQL is selecting which rows to include by using the WHERE clause. For example, WHERE rate_code = &#39;1&#39; returns only rows where rate_code exactly matches &#39;1&#39;, while WHERE rate_code != &#39;1&#39; excludes those rows. It&#39;s also crucial to remember that SQL uses three-valued logic — any boolean expression can evaluate to true, false, or NULL. If rate_code is NULL, it&#39;s neither = &#39;1&#39; nor != &#39;1&#39;, so such rows will not appear in either query. Understanding how SQL treats NULL values helps ensure accurate filtering and prevents unintended query results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixad76ehRtIxLGbJ3AewPw.png" /></figure><h3>Excluding Specific Values with NOT IN</h3><p>In standard SQL, the condition rate_code NOT IN (&#39;1&#39;, &#39;2&#39;) is effectively translated to:</p><pre>NOT (rate_code IN (&#39;1&#39;, &#39;2&#39;))</pre><p>Which in turn requires rate_code to be neither &#39;1&#39; nor &#39;2&#39; and not NULL (because comparisons with NULL often result in an unknown boolean value, thus excluding those rows).</p><p>However, BigQuery has a nuance: rows where rate_code is NULL will also appear in the result, because BigQuery treats NULL as &quot;not matching any listed values&quot; in a NOT IN clause. In other words, rate_code NOT IN (&#39;1&#39;, &#39;2&#39;) in BigQuery will exclude only rows that explicitly match &#39;1&#39; or &#39;2&#39;, and include rows where rate_code is NULL.</p><p>In practical terms:</p><ul><li>rate_code = &#39;1&#39; or &#39;2&#39; → excluded</li><li>rate_code is anything else (including NULL) → included</li></ul><p>This difference can catch some people by surprise if they’re used to strict three-valued logic in other SQL dialects. It’s important to remember how BigQuery interprets NULL in these cases, especially when filtering out specific values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ev7RkVcWI-aoTpTT3pl9sQ.png" /></figure><h3>Basic Aggregations: Counting, Averaging, and Finding the Maximum Distance</h3><p>This query provides an at-a-glance summary of the taxi trips by returning:</p><ul><li>count(1) AS n_tripcs: The total number of trips.</li><li>avg(trip_distance) AS avg_dist: The average trip distance.</li><li>max(trip_distance) AS max_dist: The longest trip recorded.</li></ul><p>With just one query, you can quickly gauge the dataset’s overall scale and its range of trip distances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZR6SG4S8WEDtUgjjwFQ5zw.png" /></figure><h3>Conditional Aggregations and Grouping by Vendor</h3><p>In this query, we apply a CASE expression inside an aggregate function while grouping by vendor_id. Specifically, we calculate an <strong>average adjusted revenue</strong> (avg_rev_adj) based on the trip distance and apply different multipliers:</p><ul><li>Trips under 3 miles: 1.5× the original total_amount</li><li>Trips between 3 and 10 miles: <strong>no change</strong></li><li>Trips over 10 miles: 0.9× the original total_amount (a 10% discount)</li></ul><p>We also retrieve the <strong>maximum trip distance</strong> (max_dist), but only for trips where rate_code is greater than &#39;2.0&#39;. This highlights how you can combine <strong>conditional logic</strong> with <strong>grouped aggregations</strong> to compute custom metrics for each vendor_id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*op6vZRR0jurRBCTV42G0RQ.png" /></figure><h3>Combining Multiple Grouping Columns and Conditional Aggregations</h3><p>This query groups by both vendor_id and total_amount, then calculates an <strong>average adjusted revenue</strong> (avg_rev_adj) using a CASE expression. Different multipliers are applied based on the trip distance:</p><ul><li>Trips shorter than 3 miles get a <strong>50% boost</strong>.</li><li>Trips over 10 miles receive a <strong>10% discount</strong>.</li></ul><p>We also compute the <strong>average</strong> and <strong>maximum trip distances</strong> within each (vendor_id, total_amount) group. The WHERE 1=1 clause is a convenient placeholder that lets you add or remove additional conditions more easily (using comments) without breaking the query structure. Additionally, GROUP BY 1,2 is a shorthand for grouping by the first and second columns in the SELECT list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q89MnGkbxVKDqAz0X7P7OQ.png" /></figure><p><strong>Tips &amp; Tricks for Manageable </strong><strong>SELECT Statements</strong><br>A neat formatting approach is to place commas at the start of each line in your SELECT clause. This way, if you want to temporarily remove a column from your query, you can simply add a -- comment marker in front of the line without worrying about trailing commas breaking your SQL syntax.</p><p>It’s especially useful when your query has many columns or uses conditional logic — quickly commenting out a column (or an entire expression) becomes much more convenient and keeps your code clean.</p><h3>Using CTEs for Summaries and Post-Aggregation Filters</h3><p>In this query, we first create a <strong>Common Table Expression (CTE)</strong> named summary, which aggregates key metrics for each vendor_id:</p><ul><li><strong>avg_rev</strong>: The average of total_amount.</li><li><strong>avg_rev_adj</strong>: The average of total_amount adjusted by a <strong>CASE</strong> expression (e.g., +50% for short trips, -10% for longer ones).</li><li><strong>avg_dist</strong>: The average trip distance.</li><li><strong>max_dist</strong>: The maximum trip distance.</li></ul><p>In the second step, we select from the summary CTE and apply a <strong>post-aggregation filter</strong> with WHERE avg_rev BETWEEN 20 AND 25. This approach lets us calculate the metrics first, then filter only the summarized results — rather than filtering on raw rows. Such a pattern is both cleaner and more efficient for downstream analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mopV6JauaenpKrGjElE4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*n4NJkeMu1TwJWERN7WcZpQ.png" /></figure><h3>Filtering Before or After Aggregation: Why We Don’t Always Need HAVING</h3><p>In this example, we apply WHERE vendor_id = &#39;1&#39; <strong>after</strong> we&#39;ve already aggregated data in the CTE (summary). However, if you know your final results won&#39;t change by filtering out rows <strong>before</strong> aggregating, you could include vendor_id = &#39;1&#39;in the <strong>original</strong> query&#39;s WHERE clause. This approach is often more efficient because the query engine can skip unnecessary rows earlier — sometimes referred to as <strong>predicate pushdown</strong> — rather than aggregating the entire dataset and filtering afterward.</p><ul><li><strong>WHERE</strong>: Filters rows <strong>before</strong> grouping or aggregation (if used in the main query).</li><li><strong>HAVING</strong>: Filters rows <strong>after</strong> they&#39;ve been grouped or aggregated.</li></ul><p>If your condition references a column used for grouping (like vendor_id), placing it in WHERE rather than HAVING can reduce the amount of data scanned and speed up your queries, as long as it doesn&#39;t alter the intended logic of your final aggregation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ae2GOpsL0WIMbBzg2a2-Ew.png" /></figure><h3>Applying the HAVING Clause for Post-Aggregation Filtering</h3><p>This query <strong>groups</strong> the table by vendor_id (noted as <strong>GROUP BY 1</strong>, referencing the first column in the SELECT list) and computes metrics such as:</p><ul><li><strong>avg_rev</strong>: Average of total_amount</li><li><strong>avg_rev_adj</strong>: An adjusted average total amount using a CASE expression</li><li><strong>avg_dist</strong>: Average trip distance</li><li><strong>max_dist</strong>: Maximum trip distance</li></ul><p>Then, the <strong>HAVING avg_rev BETWEEN 20 AND 25</strong> condition filters vendors <strong>after</strong> the aggregation step, returning only those whose average revenue falls within that numeric range. Unlike WHERE, which filters rows before aggregation, HAVINGapplies to the summarized results, making it ideal for constraining or refining groups based on aggregated values.</p><p>The comment about “group by 1, 2” simply means there’s only one non-aggregate column (vendor_id) here; there&#39;s no second grouping column to reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itxEs88RYbo0cL0f-pUf1A.png" /></figure><h3>Using EXTRACT for Hourly Grouping and Sorting</h3><p>This query <strong>extracts</strong> the hour (hour) from the pickup_datetime column and assigns it the alias <strong>hh24</strong>. We then group by hh24 to count the number of trips (count(1)), and finally <strong>ORDER BY hh24 DESC</strong> (late hours to early hours). You could specify <strong>ASC</strong> if you prefer ascending order instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lH-YxOVE8K3FtqdiwATIHg.png" /></figure><p><strong>Tips &amp; Tricks</strong></p><ul><li><strong>Reusing Aliases</strong>: Once you define an alias in the SELECT clause (e.g., hh24), you can use it directly in the GROUP BYand ORDER BY clauses.</li><li><strong>Explicit Ordering</strong>: Always specify whether you want your results sorted in ASC or DESC order for clarity and to avoid any default ordering surprises.</li><li><strong>Naming Conventions</strong>: Using an alias like hh24 can help differentiate 24-hour time references from AM/PM-based time fields.</li></ul><h3>Self-Joining Hourly Aggregates with a One-Hour Offset (Using LEFT JOIN)</h3><h4><strong>Building the Hourly Aggregates</strong></h4><p>This query first creates a Common Table Expression (CTE) named hour_stats by grouping the taxi trips dataset by the <strong>extracted hour</strong> (EXTRACT(HOUR FROM pickup_datetime)) and calculating the sum of the passenger counts (SUM(passenger_count)).</p><h4><strong>One-Hour Offset and Preserving All Rows</strong></h4><ul><li>We <strong>join</strong> the hour_stats table to itself, shifting the hour by <strong>+1</strong> to compare consecutive hours side by side.</li><li>A <strong>LEFT JOIN</strong> ensures every row from t1 (the left table) appears, even if there is no matching row in t2. This preserves data for the final hour or any hour without a next-hour match.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugU7TejhuQ1rXtqHgRBqwA.png" /></figure><p><strong>Tips &amp; Tricks</strong></p><ul><li><strong>Preserving Rows</strong>: If a matching record in t2 doesn&#39;t exist (for instance, if the &quot;next hour&quot; is missing), LEFT JOINwill still keep the row from t1 intact.</li><li><strong>Avoiding Gaps</strong>: By adding 1 to t1.hh24, you can easily compare each hour&#39;s passenger sum with the subsequent hour&#39;s sum in one query.</li></ul><h3>Self-Joining Hourly Aggregates with a Circular Offset</h3><h4><strong>Building the Hourly Aggregates</strong></h4><p>Similar to the previous query, we start by creating a hour_stats CTE that groups rows by <strong>hour</strong> and sums the total number of passengers.</p><h4><strong>Circular Offset (Wrapping 23 Back to 0)</strong></h4><p>Here, the <strong>CASE</strong> expression checks if hh24 is under 23. If so, it adds 1 to create a normal offset. If hh24 is 23, it resets to <strong>0</strong>, creating a <strong>circular</strong> mapping.</p><p>By using a <strong>regular JOIN</strong> (equivalent to an <strong>INNER JOIN</strong>), we only keep pairs where the next hour exists (including wrapping 23 to 0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4i1nc0QcgQwipzQaeo86UQ.png" /></figure><p><strong>Tips &amp; Tricks</strong></p><ul><li><strong>Circular Logic</strong>: Shifting 23 to 0 allows you to wrap the hourly sequence, so you never end up with a NULL for the 24th hour.</li><li><strong>Comparing Hours</strong>: This technique is handy when analyzing <strong>continuous or daily data</strong> where the last hour flows directly into the first hour (e.g., a 24-hour cycle).</li></ul><h3>Layered Filtering and Aggregation with Multiple CTEs</h3><p>This query demonstrates <strong>how to chain multiple Common Table Expressions (CTEs)</strong> to pinpoint top-performing hours and vendors, then calculate total revenue for those vendors.</p><h4><strong>top_hh24 CTE</strong></h4><ul><li>First, we extract the <strong>date</strong> and <strong>hour</strong> from each trip’s pickup_datetime.</li><li>We then count the total trips (n) per <strong>(day, hour)</strong> pair.</li><li>Next, we group by hh24 (the hour) to calculate the <strong>average number of trips</strong> across all days (AVG(n)), then <strong>sort</strong> and pick the <strong>top 3</strong> busiest hours.</li></ul><pre>WITH top_hh24 AS (<br>  SELECT hh24,<br>         AVG(n) AS num_avg_trip<br>  FROM (<br>    SELECT EXTRACT(DATE FROM pickup_datetime) AS day,<br>           EXTRACT(HOUR FROM pickup_datetime) AS hh24,<br>           COUNT(1) AS n<br>    FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022`<br>    GROUP BY 1, 2<br>  ) foo<br>  GROUP BY 1<br>  ORDER BY 2 DESC<br>  LIMIT 3<br>),<br>...</pre><h4><strong>top_vendor CTE</strong></h4><p>We create a top_vendor CTE where we <strong>join</strong> the main taxi table (t1) to top_hh24 on matching hours. This narrows the dataset to only the <strong>top 3 busiest hours</strong> found in the previous step.</p><p>For each (date, vendor_id) combination in those busy hours, we <strong>sum</strong> the passenger count (n_pass).<br>We then group by vendor_id again to get the <strong>average passenger count</strong> (AVG(n_pass)) and pick the <strong>top 3</strong> vendors (i.e., those who have the highest average number of passengers during the top hours).</p><pre>top_vendor AS (<br>  SELECT vendor_id,<br>         AVG(n_pass)<br>  FROM (<br>    SELECT EXTRACT(DATE FROM pickup_datetime) AS day,<br>           vendor_id,<br>           SUM(COALESCE(passenger_count, 0)) AS n_pass<br>    FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022` t1<br>    JOIN top_hh24 t2 <br>      ON (EXTRACT(HOUR FROM t1.pickup_datetime) = t2.hh24)<br>    GROUP BY 1, 2<br>  ) foor<br>  GROUP BY 1<br>  ORDER BY 2 DESC<br>  LIMIT 3<br>)</pre><ul><li>Finally, we <strong>join</strong> the main table with the top_vendor CTE using vendor_id.<br>We <strong>sum</strong> the total_amount for those vendors across <strong>all trips</strong> (not just the top hours), giving us the overall revenue of the previously selected top vendors.</li></ul><pre>SELECT vendor_id,<br>       SUM(total_amount) AS total_revenue<br>FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022`<br>JOIN top_vendor USING (vendor_id)<br>GROUP BY 1;</pre><p><strong>Tips &amp; Tricks</strong></p><ul><li><strong>Layered CTEs</strong>: Break complex analysis into logical steps — first identify top hours, then filter down to top vendors, then compute final metrics.</li><li><strong>Targeted JOINs</strong>: By joining only on the busiest hours (top_hh24), you avoid scanning the full dataset unnecessarily in the second step.</li><li><strong>COALESCE</strong>: Using COALESCE(passenger_count, 0) ensures that if passenger_count is NULL, it&#39;s treated as zero instead of skipping or breaking your sums.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwbMYtoKQUIgU6HXXJsRCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*M9f1wmKH1ksd4dmdaDyb0A.png" /></figure><h3>Detecting Potential Outliers Using a 3-Sigma Rule</h3><h4><strong>Computing Route-Specific Statistics (`</strong><strong>summary_statistics` CTE)</strong></h4><pre>WITH summary_statistics AS (<br>  SELECT <br>    pickup_location_id,<br>    dropoff_location_id,<br>    AVG(elapsed) - 3 * STDDEV(elapsed) AS min_elapsed,<br>    AVG(elapsed) + 3 * STDDEV(elapsed) AS max_elapsed<br>  FROM (<br>    SELECT <br>      pickup_location_id,<br>      dropoff_location_id,<br>      DATETIME_DIFF(dropoff_datetime, pickup_datetime, MINUTE) AS elapsed<br>    FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022`<br>    WHERE DATETIME_DIFF(dropoff_datetime, pickup_datetime, MINUTE) &gt; 0<br>  )<br>  GROUP BY 1, 2<br>)</pre><ul><li>elapsed is the trip duration in minutes. We <strong>exclude</strong> rows where dropoff_datetime &lt;= pickup_datetime to avoid zero or negative durations.</li><li>For each unique (pickup_location_id, dropoff_location_id) pair, we calculate:</li><li>min_elapsed = mean duration (AVG(elapsed)) minus <strong>3 ×</strong> the standard deviation</li><li>max_elapsed = mean duration plus <strong>3 ×</strong> the standard deviation</li></ul><p>These boundaries form a <strong>3-sigma</strong> interval. Trips whose durations fall <strong>outside</strong> ([min_elapsed, max_elapsed]) are considered <strong>outliers</strong> relative to that route&#39;s typical duration.</p><h4>Flagging Potential Outliers</h4><pre>SELECT *<br>FROM (<br>  SELECT<br>    NOT (<br>      DATETIME_DIFF(dropoff_datetime, pickup_datetime, MINUTE)<br>      BETWEEN min_elapsed AND max_elapsed<br>    ) AS is_fraud,<br>    min_elapsed,<br>    max_elapsed,<br>    DATETIME_DIFF(dropoff_datetime, pickup_datetime, MINUTE) AS elapsed,<br>    t1.*<br>  FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2022` AS t1<br>  LEFT JOIN summary_statistics AS t2<br>    USING (pickup_location_id, dropoff_location_id)<br>) foo<br>WHERE is_fraud<br>LIMIT 10;</pre><ul><li>We <strong>LEFT JOIN</strong> the main taxi table (t1) with summary_statistics (t2) on matching (pickup_location_id, dropoff_location_id).</li><li>We compute a boolean column <strong>is_fraud</strong> by checking if a trip&#39;s elapsed duration <strong>is not</strong> (NOT) between its route&#39;s min_elapsed and max_elapsed.</li><li>If the route has no matching record in summary_statistics, then min_elapsed and max_elapsed will be NULL, so the BETWEEN check is UNKNOWN, and NOT UNKNOWN is also UNKNOWN (which does not evaluate to TRUE). Thus, such rows will <strong>not</strong>appear in the final WHERE is_fraud filter.</li><li>Finally, WHERE is_fraud filters for <strong>only</strong> those trips that fall outside the 3-sigma duration range, returning up to 10 rows.</li></ul><h4><strong>Why Use a 3-Sigma Rule?</strong></h4><ul><li>3-Sigma (<strong>3 Standard Deviations</strong>) is a common heuristic to flag data points that deviate significantly from the mean in a roughly normal distribution.</li><li>Trips whose durations lie beyond μ ± 3σ (μ = average duration, σ = standard deviation) may be unusual enough to require closer scrutiny — these might indicate potential errors, extraordinary traffic conditions, or even fraudulent activity.</li></ul><p><strong>Key Observations and TipsCTE for Pre-Aggregation</strong></p><p><strong>CTE for Pre-Aggregation</strong>: By computing statistics (mean and standard deviation) in a <strong>CTE</strong>, you keep your query structure clean and avoid recalculating metrics repeatedly.</p><p><strong>LEFT JOIN Behavior</strong>:</p><ul><li>If a (pickup_location_id, dropoff_location_id) does not appear in summary_statistics, min_elapsed and max_elapsed will be NULL. As a result, the BETWEEN comparison becomes UNKNOWN, and thus is_fraud is FALSE or not included when filtering.</li><li>This design ensures you only mark a trip as an outlier if there’s a valid statistical baseline for that specific route.</li></ul><p><strong>Interpretation Nuances</strong>:</p><ul><li>is_fraud is just a label indicating a trip&#39;s duration is well outside the expected range. Actual fraud detection could require additional checks or business logic.</li><li>You can adjust the <strong>threshold</strong> (e.g., 2-sigma or 4-sigma) depending on how strict or lenient you want your outlier detection to be.</li></ul><p>By defining a confidence interval (or “acceptable range”) around the average travel time per route, you get a quick way to spot rides that deviate strongly from the norm — useful in anomaly detection, quality checks, or further fraud investigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F796KGMKbybTYbfMUi9jKg.png" /></figure><h3>Creating a Permanent Snapshot with CREATE TABLE ... AS SELECT</h3><h4><strong>Freezing the Data</strong>:</h4><ul><li>By using CREATE TABLE ... AS SELECT, you create a <strong>frozen snapshot</strong> of the source table at the time of creation. Any subsequent modifications to the underlying table (tlc_yellow_trips_2022) will <strong>not</strong> appear in this newly created table.</li></ul><h4><strong>Reusable Table</strong>:</h4><ul><li>Storing aggregated statistics in a permanent table (summary_statistics) allows you to query it repeatedly without re-computing these values. This can improve both query <strong>performance</strong> and <strong>cost-efficiency</strong> if you plan to run multiple analyses on these stats.</li></ul><h4><strong>Dropping or Overriding the Table</strong>:</h4><ul><li>If you no longer need summary_statistics, you can simply <strong>drop</strong> it:</li></ul><pre><br> DROP TABLE `sqlexercises-445807.practice_data.summary_statistics`;<br></pre><ul><li>If you want to <strong>refresh</strong> the table’s contents with updated data, you could use:</li></ul><pre><br> CREATE OR REPLACE TABLE `sqlexercises-445807.practice_data.summary_statistics` AS …</pre><p>This overrides the existing table with a brand-new snapshot.</p><ul><li>However, <strong>dropping</strong> is usually the simplest route if you’re finished with the table altogether.</li></ul><p>By creating a dedicated summary table, you gain a stable reference for outlier detection or further analytics, ensuring consistency in your results even if the underlying source data changes later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DkJIt_iouQWxv-WXMCJEBA.png" /></figure><h3>Measuring the Average Deviation from Each Vendor’s Maximum Fare</h3><h4><strong>Calculating </strong><strong>drift with a Window Function:</strong></h4><ul><li>Inside the subquery, for every row, we calculate drift by <strong>subtracting</strong> the <strong>maximum </strong><strong>total_amount</strong> (per vendor_id) from the row&#39;s own total_amount. This is done via a <strong>window function</strong>.</li><li>The result (drift) indicates how far (positively or negatively) each ride&#39;s total_amount is from that vendor&#39;s <strong>maximum</strong> fare amount.</li></ul><h4><strong>Taking the Absolute Value</strong>:</h4><ul><li>Because some drift values will be negative (for rides below the max), we apply <strong>ABS(drift)</strong> to avoid dealing with negative numbers. This allows us to measure <strong>absolute deviations</strong> rather than directional differences.</li></ul><h4><strong>Averaging the Deviations</strong>:</h4><ul><li>In the outer query, we <strong>group by </strong><strong>vendor_id</strong> and compute <strong>AVG(ABS(drift))</strong> — essentially the <strong>mean absolute deviation</strong> from each vendor&#39;s maximum fare.</li><li>The alias mae stands for <strong>Mean Absolute Error</strong> (or in this context, <strong>Mean Absolute Deviation</strong>), capturing the average gap between each ride&#39;s fare and the vendor&#39;s single highest fare.</li></ul><p>This query is useful if you want to understand, on average, <strong>how much less</strong> each vendor’s rides typically cost compared to their <strong>highest</strong> single fare — and it leverages window functions, arithmetic, and grouping to derive that insight in a single SQL statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYDpRyMqAP9dYr_8q8oVgA.png" /></figure><h3>Demonstrating Different Window Functions for Rolling and Cumulative Totals</h3><p>Below is an example query that highlights how <strong>window functions</strong> behave under different conditions, especially when you introduce an <strong>ORDER BY</strong> clause and specify <strong>ROWS BETWEEN ... AND ...</strong> or <strong>RANGE BETWEEN ... AND ...</strong>.</p><h4><strong>Summation Without Ordering</strong></h4><ul><li>SUM(total_rev) OVER (PARTITION BY vendor_id)</li><li>This calculates the <strong>total</strong> of total_rev <em>across all years</em> for each vendor (i.e., the total revenue for that vendor in the entire dataset). There is <strong>no</strong> ordering, so every row for the same vendor receives the same total.</li></ul><h4><strong>Cumulative Total (Ordered by Year)</strong></h4><ul><li>SUM(total_rev) OVER (PARTITION BY vendor_id ORDER BY year)</li><li>Adding ORDER BY year transforms the function into a <strong>running total</strong>: each row includes the sum of that year&#39;s total_rev <strong>plus all previous years</strong> for the same vendor.</li></ul><h4><strong>Moving Sum Over a Bounded Window</strong></h4><ul><li>SUM(total_rev) OVER (PARTITION BY vendor_id ORDER BY year ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)</li><li>Here, we define a <strong>moving window</strong> of three rows: one before the current row, the current row, and one after the current row (based on the <strong>physical row order</strong> of year). This sums total_rev for these three consecutive years for each vendor, which can be useful for <strong>year-over-year</strong> comparisons in a sliding manner.</li></ul><h4><strong>Moving Average (Rows-Based)</strong></h4><ul><li>AVG(total_rev) OVER (PARTITION BY vendor_id ORDER BY year ROWS BETWEEN 3 PRECEDING AND CURRENT ROW)</li><li>This calculates the <strong>average</strong> of total_rev over the last <strong>3 rows plus the current row</strong> (total of 4 rows) when traversing by year. For instance, for year = 2022, the window includes 2019, 2020, 2021, and 2022 (assuming those rows exist).</li></ul><h4><strong>Moving Average (Range-Based)</strong></h4><ul><li>AVG(total_rev) OVER (PARTITION BY vendor_id ORDER BY year RANGE BETWEEN 3 PRECEDING AND CURRENT ROW)</li><li>RANGE uses the <strong>value</strong> of the ORDER BY column (here, year) to define the window. In many SQL engines, RANGEwith 3 PRECEDING can mean &quot;3 units back in the sort column&quot; rather than &quot;3 rows back.&quot;</li><li>Depending on how BigQuery handles RANGE with a non-numeric or non-continuous ordering column, the results may differ from the ROWS version. Typically, RANGE BETWEEN 3 PRECEDING AND CURRENT ROW makes the most sense when year is numeric or continuous (e.g., numeric timestamps).</li><li>In BigQuery, using RANGE on a discrete column like year can sometimes produce the same result as ROWS, but the underlying logic differs: RANGE is about the <strong>value range</strong>, while ROWS is about <strong>physical row positions</strong> in the partition.</li></ul><h4><strong>Understanding Window Framing Clauses</strong></h4><ul><li><strong>ROWS BETWEEN ... AND ...</strong>:<br>Operates on the <strong>physical offset</strong> of rows in the ordered partition. For example, 3 PRECEDING is literally the <strong>three previous rows</strong>, regardless of the values in those rows.</li><li><strong>RANGE BETWEEN ... AND ...</strong>:<br>Operates on the <strong>value</strong> of the ordering column. For instance, 3 PRECEDING can mean &quot;values within 3 units of the current row&#39;s ordering value.&quot; If the ordering column is discrete (like integer years), the distinction may be subtle. If the ordering column is continuous (like timestamps or numeric fields), RANGE can yield different windows than ROWS.</li></ul><h4><strong>Key Takeaways</strong></h4><p>ORDER BY in a Window Function:</p><ul><li>Transforms a simple aggregation (like a total) into a <strong>cumulative</strong> or <strong>moving</strong> calculation.</li><li>You can track trends over time, compare adjacent rows, or compute rolling averages.</li></ul><p>ROWS vs. RANGE:</p><ul><li>ROWS focuses on a <strong>fixed number</strong> of rows around the current row.</li><li>RANGE focuses on a <strong>value-based interval</strong> in the ordering column.</li></ul><h4><strong>Use Cases</strong></h4><ul><li><strong>Cumulative totals</strong> (... ORDER BY ...) for year-to-date metrics.</li><li><strong>Moving windows</strong> with ROWS for adjacent-year or adjacent-month comparisons.</li><li><strong>Value-based windows</strong> with RANGE for dynamic intervals, such as &quot;within 7 days&quot; or &quot;within 3 units of the current measurement.&quot;</li></ul><p>By mixing <strong>PARTITION BY</strong>, <strong>ORDER BY</strong>, and window framing clauses (e.g., ROWS BETWEEN or RANGE BETWEEN), you gain deep control over how you compute rolling, cumulative, or sliding analytics in a single SQL query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTAY912OmbkRINBQ_bTD3A.png" /></figure><h3>Selecting the Top 2 Revenue Years for Each Vendor</h3><p>This query identifies the <strong>two years</strong> in which each vendor earned the <strong>highest total revenue</strong> from taxi rides:</p><h4><strong>Summarizing Revenue by (Year, Vendor)</strong></h4><ul><li>In the <strong>innermost subquery</strong>, we <strong>extract</strong> the <strong>year</strong> from pickup_datetime and <strong>group by</strong> (year, vendor_id).</li><li>We <strong>sum</strong> total_amount to determine how much each vendor earned in each year (aliased as total_rev).</li></ul><h4><strong>Ranking Each Vendor’s Rows</strong></h4><ul><li>In the <strong>outer subquery</strong>, we apply ROW_NUMBER() OVER (PARTITION BY vendor_id ORDER BY total_rev DESC) AS rn.</li><li>This assigns a <strong>rank</strong> to each (year, vendor_id) pair based on its revenue, with <strong>1</strong> corresponding to the highest revenue for that vendor, <strong>2</strong> to the second highest, and so on.</li></ul><h4><strong>Filtering for the Top 2 Years</strong></h4><ul><li>The final WHERE rn &lt;= 2 statement <strong>retains only the rows</strong> with rank 1 or 2. In other words, we get the <strong>top two</strong>revenue-generating years per vendor.</li><li>We then <strong>ORDER BY vendor_id, year</strong> to view the results grouped by vendor in ascending chronological order.</li></ul><p>This pattern — calculating an <strong>aggregate metric</strong> by group, then <strong>ranking</strong> within each group — is common for “top-N” queries, making it easy to see the best-performing categories (in this case, years) for each partition (vendor).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4n33ByxsBHsEyTl5LBMmqg.png" /></figure><h3>Identifying Frequently Top-Ranked Drop-Off Locations</h3><p>Below is a query designed to find drop-off locations that consistently place in the <strong>top 5</strong> (by ride count) across multiple months. We then highlight locations that appear in these top rankings for <strong>more than five months</strong> and calculate their average rank.</p><h4><strong>Monthly Ride Counts (Innermost Subquery)</strong></h4><ul><li>We <strong>extract</strong> the <strong>year (</strong><strong>y)</strong> and <strong>month (</strong><strong>m)</strong> from dropoff_datetime, then group by (y, m, dropoff_location_id).</li><li>COUNT(1) AS n gives the total rides for each (year, month, dropoff_location_id).</li><li>Results are ordered by (y, m, n DESC) for readability, though the ordering does not affect the ranking step.</li></ul><h4><strong>Applying </strong><strong>DENSE_RANK and Filtering Top 5</strong></h4><ul><li>We apply a <strong>window function</strong>:</li></ul><pre>DENSE_RANK() OVER (PARTITION BY y, m ORDER BY n DESC) AS r</pre><p>This ranks each drop-off location by <strong>ride count</strong> within its month (partitioned by (y, m)), with <strong>no gaps</strong> in rank numbers if there are ties.</p><ul><li>QUALIFY r &lt;= 5 keeps only the <strong>top 5</strong> locations per month.</li></ul><h4><strong>Aggregating Final Results</strong></h4><p>In the outer query, we group by dropoff_location_id and compute:</p><ul><li><strong>AVG(r) AS avg_rank</strong>: The <strong>average</strong> of the rank values (1 through 5) the location earned across the months it appeared in the top 5.</li><li><strong>COUNT(1) AS months_in_top_5</strong>: The number of months the location placed in the top 5.</li></ul><p>We <strong>filter</strong> for locations that appeared in the top 5 for <strong>more than five months</strong> (HAVING COUNT(1) &gt; 5). Finally, we order by the avg_rank (ascending) and limit the result to 10 rows.</p><h4><strong>Why This Matters</strong></h4><ul><li><strong>Consistent High Performers</strong>: This query pinpoints drop-off locations that aren’t just popular once or twice, but maintain a top spot across several months.</li><li><strong>Dynamic Ranking</strong>: DENSE_RANK ensures locations with the same ride count share the same rank, making the ranking fair.</li><li><strong>Flexible Thresholds</strong>: You can adjust the r &lt;= 5 condition to examine top 3, top 10, etc., or modify HAVING COUNT(1) &gt; 5 to require a different persistence threshold.</li></ul><p>By combining <strong>monthly ride counts</strong>, <strong>window functions</strong>, and <strong>final aggregation</strong>, you gain a multifaceted view of which drop-off locations truly dominate month after month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcUkhkP2SDV6Iv-VjMAJFQ.png" /></figure><h3>Tracking Consecutive Citi Bike Trips on the Same Bike</h3><p>Below is a query that <strong>chains</strong> two consecutive Citi Bike trips together if they involve the <strong>same bike</strong> and occur at the <strong>same station</strong> (end station of the first trip = start station of the next trip), within a <strong>15-minute</strong> window. This effectively shows how a single bike moves from one station to another in two consecutive trips.</p><h4><strong>Self-Join on the Citi Bike Trips Table</strong></h4><ul><li>The query references the <strong>same table</strong> twice — aliased as ft (&quot;first trip&quot;) and st (&quot;second trip&quot;).</li><li>We apply the same filter (tripduration IS NOT NULL) to each subquery so that only valid trips are considered.</li></ul><h4><strong>Matching Bike &amp; Station</strong></h4><ul><li>ft.bikeid = st.bikeid: Both trips must use the <strong>same bike</strong>.</li><li>ft.end_station_id = st.start_station_id: The end station of the first trip is the start station of the second trip, establishing a logical connection where the bike could immediately be reused from the same station.</li></ul><h4><strong>Time Constraints</strong></h4><ul><li>ft.stoptime &lt; st.starttime: Ensures the second trip actually starts <strong>after</strong> the first trip ends.</li><li>ft.stoptime + INTERVAL 15 MINUTE &gt; st.starttime: Constrains the gap to <strong>no more than 15 minutes</strong>, implying the second trip happens relatively soon after the first trip finishes.</li></ul><h4><strong>Columns Selected</strong></h4><ul><li>bikeid: The unique identifier for the bike.</li><li>starttime (from ft): When the first trip began.</li><li>start_station_id (from ft): Where the first trip started.</li><li>intermediate_station_id = ft.end_station_id: The station where the first trip ended (and the second trip began).</li><li>terminal_station_id = st.end_station_id: The station where the second trip ended.</li></ul><h4><strong>Why This Matters</strong></h4><ul><li><strong>Trip Chaining</strong>: By linking consecutive trips on the same bike, you can trace how a bike moves through multiple stations in a short time.</li><li><strong>Bike Usage Patterns</strong>: This can help identify bikes with rapid turnovers and popular station combinations — useful for logistics, rebalancing, or general usage analytics.</li><li><strong>Adjustable Window</strong>: The 15-minute window (ft.stoptime + INTERVAL 15 MINUTE &gt; st.starttime) can be tweaked to broaden or narrow the gap allowed between two trips.</li></ul><p>This approach demonstrates a <strong>self-join</strong> use case where data from the <strong>same table</strong> is combined to analyze relationships between consecutive records under defined matching and time conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKyTdTb4x04yYQYHh3R8nA.png" /></figure><h3>Finding the Most Active Citi Bike Stations</h3><p>Below are <strong>two different approaches</strong> for identifying the busiest Citi Bike stations:</p><ol><li><strong>First Query</strong>: Sums up the total rides (both as a start and end station) across all time.</li><li><strong>Second Query</strong>: Calculates a <strong>daily rank</strong> for each station and then averages those ranks, providing a more nuanced view of station popularity over multiple days.</li></ol><h4>Approach 1: Summing All Ride Counts per Station</h4><p><strong>Combining Start and End Counts</strong></p><ul><li>We have two subqueries: one calculates how many trips <strong>originated</strong> at each station, and the other calculates how many trips <strong>terminated</strong> there.</li><li>A <strong>FULL OUTER JOIN</strong> merges these sub-results by station_id. Any station that appears in either subquery will be in the final output.</li><li><strong>COALESCE(f.n, 0) + COALESCE(t.n, 0)</strong> sums ride counts, treating any missing values as zero.</li></ul><p><strong>Single Snapshot of Activity</strong></p><ul><li>The final output shows the <strong>total rides</strong> (as start or end) over the entire dataset, returning the top 5 stations by this combined volume.</li><li>This is a <strong>straightforward approach</strong> if you only want <strong>overall</strong> busiest stations without regard for time trends.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jiqJ3VNCwxp7jnnc4yc65A.png" /></figure><h4>Approach 2: Ranking Stations by Day and Averaging Their Ranks</h4><p><strong>Counting Rides by Day and Station</strong></p><p>We take the <strong>union</strong> of:</p><ul><li>Trips <strong>originating</strong> at a station for each day.</li><li>Trips <strong>ending</strong> at a station for each day.</li></ul><p>Then, for each (day, station) pair, we <strong>sum</strong> the number of rides (n) to get the total daily usage of that station (both in and out).</p><p><strong>Daily Rankings with </strong><strong>DENSE_RANK</strong></p><ul><li>We apply a <strong>window function</strong>:</li></ul><pre>DENSE_RANK() OVER (PARTITION BY day ORDER BY n DESC) AS rnk</pre><p>This assigns <strong>daily ranks</strong> based on station usage. Stations with the highest daily rides get rnk=1, the next gets rnk=2, etc. Ties share the same rank.</p><p><strong>Averaging Ranks Across All Days</strong></p><ul><li>In the outer query, we group by station and take AVG(rnk), giving each station&#39;s <strong>average daily rank</strong>.</li><li>A station with a lower average rank means it is <strong>more consistently near the top</strong>.</li><li>We order by this average rank (ORDER BY avg_rank) and select the first 100 for inspection.</li></ul><h4>Why the Second Approach May Be Better</h4><p><strong>Temporal Insights</strong></p><ul><li>The first approach only looks at <strong>overall counts</strong>. A station might have very high usage on certain days but be almost unused on others, and the overall sum could overshadow that variability.</li><li>The second approach captures <strong>how a station performs daily</strong>, letting you see which stations are <strong>consistently busy</strong>over time rather than just heavily used in aggregate.</li></ul><p><strong>Fair Ranking</strong></p><ul><li>By <strong>ranking stations each day</strong>, you ensure that a station’s daily performance is considered relative to the same day’s data. If there’s a day with unusually low overall activity, each station’s share is still comparable.</li><li>Averaging those daily ranks gives a more <strong>robust</strong> measure of sustained popularity than a simple total volume count.</li></ul><p><strong>Outlier Protection</strong></p><ul><li>A single day of extremely high ridership can skew the entire usage count in the first approach. The second approach spreads the effect across many days, reducing the impact of one-off spikes.</li></ul><p><strong>Approach 1 (Summation):</strong></p><ul><li><strong>Pros</strong>: Very simple, fast, easy to read.</li><li><strong>Cons</strong>: Provides no breakdown of how activity fluctuates day-to-day or month-to-month.</li></ul><p><strong>Approach 2 (Daily Ranking + Average Rank):</strong></p><ul><li><strong>Pros</strong>: Shows <strong>consistency</strong> and <strong>sustained</strong> station popularity over time, reduces the effect of outlier days, and ranks stations <strong>relative</strong> to their peers each day.</li><li><strong>Cons</strong>: A bit more complex to write and compute.</li></ul><p>Choosing the right approach depends on whether you just want overall busiest stations or you want <strong>temporal dynamics</strong>and consistency taken into account.</p><h3>Creating a Table to Track Each Bike’s Cumulative Distance</h3><h4><strong>Filtering the Timeframe</strong></h4><ul><li>Only trips from the past 6 months are selected, based on the most recent starttime in the dataset.</li></ul><h4><strong>Distance Calculation</strong></h4><ul><li>ST_DISTANCE(...) measures the geodesic distance between the start and end coordinates. Dividing by 1000converts meters to kilometers.</li></ul><h4><strong>Cumulative Sum</strong></h4><ul><li>SUM(dist_km) OVER (PARTITION BY bikeid ORDER BY starttime) calculates how many kilometers each bike has traveled overall, in the order of its trip start times.</li></ul><h4><strong>Permanent Table</strong></h4><ul><li>The CREATE TABLE ... AS SELECT statement stores these results in practice_data.bike_trip_milage, allowing you to query or analyze cumulative distances without recalculating for every query.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2iqh-39JqmyIDho1Aa-1NQ.png" /></figure><h3>Tracking When Each Bike Hits Maintenance Thresholds</h3><p>The query below identifies the <strong>time</strong> at which each bike crosses a new <strong>maintenance threshold</strong> (every 100 km of accumulated distance). It then provides a <strong>pointer</strong> to the <strong>next</strong> maintenance time for the same bike, allowing you to see how often it moves from one threshold to the next.</p><h4>Defining a Maintenance Threshold (maintainance_index)</h4><ul><li>In the subquery, CAST(total_milage / 100 AS INT) AS maintainance_index groups each bike&#39;s trips into &quot;buckets&quot; of <strong>100 km</strong>. For example, if total_milage is 250 km, the maintainance_index is 2.</li></ul><h4>Picking One Row per (Bike, Maintenance Index)</h4><ul><li>Using ROW_NUMBER() OVER (PARTITION BY bikeid, maintainance_index ORDER BY total_milage DESC) AS rn ranks rows within <strong>each</strong> (bikeid, maintainance_index) group by total_milage in descending order.</li><li>QUALIFY rn = 1 retains only the row <strong>with the highest </strong><strong>total_milage</strong> in that threshold bucket. This effectively picks the point in time when the bike has definitively crossed into the new 100 km bracket.</li></ul><h4>Identifying the Next Maintenance Time</h4><ul><li>In the final SELECT, LEAD(starttime) OVER (PARTITION BY bikeid ORDER BY maintainance_index) looks <strong>ahead</strong> to the <strong>next</strong> threshold&#39;s starttime for the same bike.</li><li>For each maintenance threshold, you get:</li><li><strong>maint_time</strong>: When the bike crosses the current threshold.</li><li><strong>next_maint_time</strong>: When it crosses the <strong>next</strong> threshold.</li></ul><p>The output gives a row for each (bikeid, maintainance_index), showing <strong>when</strong> the bike reached that threshold and <strong>when</strong> it will reach (or did reach) the following one.</p><p>This approach is handy for <strong>maintenance scheduling</strong> or usage analysis. You can see how quickly each bike moves from one mileage bracket to the next and plan maintenance intervals accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aV7Ii6Af4XROIh8t-Zsv9Q.png" /></figure><h3>Analyzing the Average Number of Days Between Maintenance Intervals</h3><p>Below is a query that calculates, for each bike, how many days elapse between successive <strong>maintenance thresholds</strong>(every 200 km), and then computes the <strong>average</strong> of these intervals. The LIMIT 10 simply returns a small sample of the aggregated results rather than the full dataset.</p><h4>Defining Maintenance Buckets (maintainance_index)</h4><ul><li>In the sub-subquery, CAST(total_milage / 200 AS INT) lumps each bike&#39;s trips into intervals of <strong>200 km</strong>.</li><li>For instance, if a bike’s cumulative mileage (total_milage) is 450 km, its maintainance_index is 2.</li></ul><h4>Selecting the Milestone Trip per Interval</h4><ul><li>ROW_NUMBER() OVER (PARTITION BY bikeid, maintainance_index ORDER BY total_milage DESC) AS rnranks rows within each (bikeid, maintainance_index) group by <strong>descending</strong> total_milage.</li><li>QUALIFY rn = 1 keeps only the <strong>single row</strong> that represents the point at which the bike definitely entered (or surpassed) that 200-km bracket. This is the &quot;maintenance milestone&quot; trip.</li></ul><h4>Computing Consecutive Maintenance Times</h4><ul><li>In the next layer, for each bike and maintenance index, we use:</li></ul><pre>LEAD(starttime) OVER (PARTITION BY bikeid ORDER BY maintainance_index)</pre><p>to get the <strong>start time</strong> of the <strong>next</strong> maintenance milestone (next_maint_time).</p><h4>Interval in Days (inter_maint_day)</h4><ul><li>We calculate the gap between the current milestone (maint_time) and the next milestone (next_maint_time) in <strong>days</strong> with:</li></ul><pre>DATETIME_DIFF(next_maint_time, maint_time, DAY)</pre><ul><li>This value (inter_maint_day) tells us how long it takes (in days) for the bike to cover <strong>another</strong> 200 km.</li></ul><h4>Averaging Interval Length</h4><ul><li>Finally, the outer query takes AVG(inter_maint_day) — the <strong>mean</strong> days between maintenance milestones — across all bikes and intervals.</li><li>The LIMIT 10 restricts the result set to 10 rows, which is somewhat unusual with an aggregate, but may be used here for demonstration or to preview partial results.</li></ul><h4>Practical Use Case</h4><p>This approach helps <strong>estimate how many days</strong> it typically takes a bike to move from one 200-km maintenance threshold to the next. It can be applied to schedule tune-ups or plan service intervals based on <strong>actual usage</strong> rather than just time alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCvTXFAfYyJKSMExwiSgcA.png" /></figure><p>For any questions, clarifications, or further discussions about the examples covered in this article, feel free to reach out. It’s always a pleasure to exchange ideas and help fellow data enthusiasts on their journey toward deeper insights and better data practices!</p><p>Advanced SQL techniques open doors to richer, more efficient analytics — even with massive datasets like the NYC Taxi Trips. Applying concepts like window functions, CTEs, and conditional logic can transform a simple query into a powerful exploration tool. Whether the goal is detecting outliers, scheduling maintenance, or finding top-ranked categories, the strategies showcased here illustrate how to push SQL beyond the basics in BigQuery.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0067f94ccab8" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/exploring-advanced-sql-functions-in-bigquery-with-the-nyc-taxi-trips-dataset-0067f94ccab8">Exploring Advanced SQL Functions in BigQuery with the NYC Taxi Trips Dataset</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>