Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Query challenge
Message
De
07/08/2009 08:08:27
Cetin Basoz
Engineerica Inc.
Izmir, Turquie
 
 
À
06/08/2009 16:13:50
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Titre:
Versions des environnements
SQL Server:
SQL Server 2000
Application:
Desktop
Divers
Thread ID:
01416576
Message ID:
01416708
Vues:
77
>Each period (basically monthly) I need to generate a commission report for every seller. I have a commission table and to get the data I do something similar to this:
>
>
>SELECT a.Period_id, a.SellerId,
>           (SELECT SUM(Amount) FROM Commission WHERE SellerId = a.SellerId AND Period_id < a.Period_id) AS Balance              
>FROM Commission a
>
>
>With this query, I getall the transactions and an extra field with a balance of previous periods, this is done with the "SELECT SUM(amount)...", this is repeated for every transaction record but no biggie, it's there, I get the data and generate the report no problem.
>
>This is the problem; lets say we are printing period MAR 2009 and a seller has no transactions for this period, then 2 things can happen:
>1) There's no balance for periods before MAR 2009, so the report doesn't print for the seller (no problem)
>2) There's a balance for periods before MAR 2009, so the report has to print for the seller (problem)
>
>so in situation #2 since there are no records for MAR 2009 then it doesn't get to SUM to get the beginning balance. I need to somehow include in my cursor the ones that have no transactions but a previous balance so it can print in my report (basically will show the balance and the rest will be 0 since there are no transactions). I have an idea of how to do this with 2 queries and some processing in foxpro but maybe there's a better way to do it in one query.
>
>Any ideas?
>
>Thanks.

If I understood you right:
declare @period_ID int
declare @tally table(n int)

set @period_ID = 3

insert into @tally select top (@period_id) row_number() over (ORDER BY t1.Object_ID) AS N
   FROM Master.sys.All_Columns t1
	CROSS JOIN Master.sys.All_Columns t2

select t3.seller_id, t3.Period_id, 
     (SELECT SUM(Amount) 
      FROM Commission 
      WHERE Seller_Id = t3.Seller_Id AND Period_id < t3.Period_id) AS Balance
from 
   (select distinct t2.seller_id, t1.N as Period_id
    from @tally t1
      cross join Commission t2) t3
where t3.Period_id = @Period_ID
Cetin
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform