 <p>You didn't specify what version of SQL you are using so I am doing this example in SQL Server where @cost_1 is a variable. You can adapt it to the syntax for whatever SQL variant you are using. The following will give you the counts you want as a SQL result set:</p> <pre><code>SELECT start_dsgn, COUNT(CASE WHEN min_cost_1 &lt;= @cost_1 OR min_cost_2 &lt;= @cost_2 THEN end_dsng END) as Cnt FROM table GROUP BY start_dsgn </code></pre> <p>Once you have that, it's up to you to convert that into whatever format you want in whichever language you are using to query the database. You also didn't specify what language you are using, but it looks like you want a dictionary where start_dsgn is the key. </p> <p>Most languages would return a list or array of either lists, tuples or dictionaries depending on what you use. From there it's pretty easy to convert them into any other form, at least in Python. Strongly typed languages like C#, Java and Swift are a little trickier.</p>