Re: T-SQL Challenge



On Wed, 17 Oct 2007 12:14:00 -0700, imani_technology_spam@xxxxxxxxx
wrote:

We have this basic SELECT statement:

SELECT product_id, we_date, sum(demand_units)
FROM weekly_transactions
WHERE demand_units > 0
GROUP BY product_id, we_date
ORDER BY product_id, we_date

However, for each Product and WE_DATE, we also want the demand units
for the previous 10 weeks. So far week ending 9/23/2007, we want the
demand_units for that week PLUS the demand_units for the previous 10
weeks. I have NOT idea how to pull this off! Can anyone out there
help me?

Hi imani_technology_spam,

SELECT a.product_id, a.we_date, SUM(b.demand_units)
FROM weekly_transactions AS a
INNER JOIN weekly_transactions AS b
ON b.product_id = a.product_id
AND b.we_date BETWEEN DATEADD(week, -10, a.we_date)
AND a.we_date
GROUP BY product_id, we_date
ORDER BY product_id, we_date;

(untested - see www.aspfaq.com/5006 if you prefer a tested reply).

--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis
.



Relevant Pages

  • Re: nulls
    ... Hugo Kornelis, SQL Server MVP ... My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis ...
    (comp.databases.ms-sqlserver)
  • Re: Date Range for SQL 2005
    ... execute. ... Hugo Kornelis, SQL Server MVP ... My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis ...
    (comp.databases.ms-sqlserver)
  • Re: reduce time for search query
    ... Posted by Peso: ... Hugo Kornelis, SQL Server MVP ... My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis ...
    (comp.databases.ms-sqlserver)
  • Re: SQL Minus 7 days from current date
    ... Hugo Kornelis, SQL Server MVP ... My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis ...
    (microsoft.public.sqlserver.mseq)
  • Re: Return Key (identity) on INSERT operation (SQL/ASP)
    ... hopefully he can expedite processing your full subscription. ... SQL Server MVP ... Columnist, SQL Server Professional ... Please reply to the newsgroup. ...
    (microsoft.public.inetserver.asp.general)