Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To make this a little more interesting I added another segment that would have the same price as an earlier segment to make sure I was separating them:</p> <pre><code>INSERT INTO prices(productKey, PriceType,BeginDate,EndDate, price) VALUES (1, 'DISCOUNT', '5-2-2010', '5-8-2010', -15) </code></pre> <p>Also I have a table called <code>tblDates</code> that is populated by the following:</p> <pre><code>INSERT dbo.tblDates (date1) SELECT TOP(65536) ROW_NUMBER()OVER(ORDER BY v1.number)-1 FROM master.dbo.spt_values v1 CROSS APPLY master.dbo.spt_values v2 WHERE v1.type='p' and v2.type='p' GO </code></pre> <p>The script I'm giving here doesn't require that. But having it couldn't hurt speed and doesn't really take up that much room. Here is my answer:</p> <pre><code>DECLARE @InitialBeginDate DATE , @FinalEndDate DATE; SELECT @InitialBeginDate = MIN(BeginDate) , @FinalEndDate = MAX(EndDate) FROM prices WHERE productKey = @ProductKey CREATE TABLE #Dates ( DateValue DATE NOT NULL ) INSERT #Dates (DateValue) SELECT DATEADD(DAY, V.number, @InitialBeginDate) FROM master..spt_values V WHERE V.[type] = 'P' AND V.number BETWEEN 0 AND DATEDIFF(DAY, @InitialBeginDate, @FinalEndDate) ;WITH MergedDays AS ( SELECT ListedDates.DateValue , SUM(P.price) PriceOnDate , DATEDIFF(DAY, @InitialBeginDate, ListedDates.DateValue) - DENSE_RANK() OVER(PARTITION BY SUM(P.price) ORDER BY ListedDates.DateValue, SUM(P.price)) DateGroup FROM #Dates ListedDates INNER JOIN prices P ON P.BeginDate &lt;= ListedDates.DateValue AND P.EndDate &gt;= ListedDates.DateValue AND P.productKey = @ProductKey GROUP BY ListedDates.DateValue ) SELECT MIN(DateValue) AS SegmentBeginDate , MAX(DateValue) AS SegmentEndDate , MAX(PriceOnDate) AS SegmentPrice -- This is just to collapse it, it'll be the same for all records. FROM MergedDays GROUP BY DateGroup ORDER BY SegmentBeginDate DROP TABLE #Dates </code></pre> <p>There are a couple other answers now, so this is just another way of doing things; there are many.</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.
    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