Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>UPDATE TO ANSWER NOW THAT DATA SAMPLES ARE AVAILABLE</p> <p>Still assuming it's Microsoft SQL Server, this query produces the following result</p> <pre><code>SELECT c.category_id, minDateExpires.Expiring FROM category c LEFT JOIN product_to_category p2c ON (c.category_id = p2c.category_id) LEFT JOIN product p ON (p2c.product_id = p.product_id) LEFT JOIN ( SELECT MIN(date_expires) AS expiring, Product_ID FROM product WHERE date_expires &gt;= GETDATE() GROUP BY Product_ID ) minDateExpires on p.product_id = minDateExpires.product_id ORDER BY expiring </code></pre> <p>Results:</p> <pre><code>category_id Expiring 63 NULL 63 NULL 62 NULL 64 NULL 63 2012-07-16 14:12:00.000 63 2012-07-18 08:15:00.000 62 2012-07-26 15:01:00.000 63 2012-08-02 13:04:00.000 63 2012-08-24 00:00:00.000 </code></pre> <p>The null columns are there because there is no min date for those product id's >= the current date/time. Are you actually after the minimum date time grouped by categoryid, not product id? In which case your query could be something like:</p> <pre><code>SELECT c.category_id, minDateExpires.Expiring FROM @category c LEFT JOIN @product_to_category p2c ON (c.category_id = p2c.category_id) LEFT JOIN @product p ON (p2c.product_id = p.product_id) LEFT JOIN ( SELECT MIN(date_expires) AS expiring, Category_ID FROM @product p join @product_to_category p2c on p2c.product_id = p.product_id WHERE date_expires &gt;= GETDATE() GROUP BY Category_id ) minDateExpires on p2c.category_id = minDateExpires.category_id ORDER BY expiring </code></pre> <p>which gives you</p> <pre><code>64 NULL 63 2012-07-16 14:12:00.000 63 2012-07-16 14:12:00.000 63 2012-07-16 14:12:00.000 63 2012-07-16 14:12:00.000 63 2012-07-16 14:12:00.000 63 2012-07-16 14:12:00.000 62 2012-07-26 15:01:00.000 62 2012-07-26 15:01:00.000 </code></pre>
    singulars
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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