Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing a Result Set From a Sub SELECT When Duplicate Rows are Encountered
    primarykey
    data
    text
    <p>First of all, the table I'm struggling with:</p> <pre><code>DispatchLocations ================= DispatchID int StopNumber int Arrived bool Departed bool </code></pre> <p>The idea is that on a trucking route, there are many stops in a dispatch. This is a list of each location on each dispatch (essentially, it's a route table). In this view, there should only be one dispatch for each row of output, which points to the "current stop" that the dispatch is at.</p> <pre><code>SELECT TOP 4 DispatchID, Min(StopNumber) AS NextStop, Arrived, Departed FROM DispatchLocations GROUP BY DispatchID, Arrived, Departed HAVING (Arrived = 0 OR Departed = 0) ORDER BY DispatchID ASC, NextStop ASC </code></pre> <p>My view's output as of now:</p> <pre><code>Dispatch_ID NextStop Arrived Departed =========== ======== ======= ======== 3 2 False False 1356 2 False False 6410 1 True False 6410 2 False False </code></pre> <p>The last row is being dumped in because the GROUP BY must include the arrival and departure status, breaking the uniqueness of the output.</p> <p>The desired rows (only) can be extracted using a very similar query:</p> <pre><code>SELECT DispatchID, Min(StopNumber) AS NextStop, Arrived, Departed FROM DispatchLocations GROUP BY DispatchID, Arrived, Departed HAVING (Arrived = 1 AND Departed = 0) AND Min(StopNumber) = 1 ORDER BY DispatchID ASC Dispatch_ID NextStop Arrived Departed =========== ======== ======= ======== 6410 1 True False 50589 1 True False 50687 1 True False </code></pre> <p>I verified these results by selecting all DispatchIDs from my view <code>WHERE COUNT(DispatchID) &gt; 1</code>. </p> <p>How can I use the results from the second query whenever I encounter those matching IDs in the view? I can't get an <code>EXIST</code> or an <code>EXCEPT</code> clause to work with <code>HAVING</code> present in the query text. So for now I'm taking the results set off the database's hands, and having the application logic sort through any duplicate results, and keeping only the first one encountered for each dispatch ID. But I'd rather have the database do this for me.</p> <h1>UPDATE</h1> <p>I'm using SSMS 2008, which builds views with a <code>TOP 100 PERCENT</code> included by default. Here's the <a href="http://pastebin.com/n8Q8i27T" rel="nofollow">pastebin</a> of the original.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload