Author |
Topic |
mjimenezh
Yak Posting Veteran
81 Posts |
Posted - 2014-10-20 : 15:18:53
|
Hi to all,I'm writing an sql 2008 view that shows me all the invoices per month and per type, I need to count all the invoices per month and per invoice type, additionally I want to show the first and the last invoice number of every month, how can I do this? I know the count process but not how I can get the first and the last invoice number, this is my code :SELECT PERCENT faknr AS InvoiceNr, dagbknr AS InvoiceType, YEAR(fakdat) AS YearNr, MONTH(fakdat) AS MonthNrFROM dbo.frhkrgWHERE (YEAR(fakdat) = YEAR(GETDATE()))ORDER BY InvoiceNr DESC ACTUAL RECORDS :InvoiceNr|InvoiceTyoe|YearNr|MonthNr|31400212 | 132 | 2014 | 10 |31400211 | 132 | 2014 | 10 |31400210 | 132 | 2014 | 10 |21400151 | 131 | 2014 | 10 |21400150 | 131 | 2014 | 10 |21400149 | 131 | 2014 | 10 |AND I need to get this YearNr|MonthNr|InvoiceType|InitialNr|FinalNr |TotalRecords| 2014 | 10 | 132 |31400210 |31400212| 3 | 2014 | 10 | 131 |21400149 |21400151| 3 | Thanks in advance |
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2014-10-20 : 15:53:25
|
[code]declare @t table (InvoiceNr int , InvoiceType int , YearNr int, MonthNr int)insert into @t (InvoiceNr,InvoiceType,YearNr,MonthNr) values (31400212 , 132 , 2014 , 10 ) , (31400211 , 132 , 2014 , 10 ) , (31400210 , 132 , 2014 , 10 ) , (21400151 , 131 , 2014 , 10 ) , (21400150 , 131 , 2014 , 10 ) , (21400149 , 131 , 2014 , 10 ) select YearNr, MonthNr, InvoiceType, InitialNr, FinalNr, TotalRecordsfrom (select YearNr, MonthNr, InvoiceType ,min(InvoiceNr) over(partition by yearnr, monthnr, InvoiceType) as InitialNr ,max(InvoiceNr) over(partition by yearnr, monthnr, InvoiceType) as FinalNr ,count(*) over(partition by yearnr, monthnr, InvoiceType) as TotalRecords ,row_number() over(partition by yearnr, monthnr, InvoiceType order by InvoiceNr) as rnfrom @t) qwhere rn = 1order by YearNr, MonthNr, InvoiceType desc[/code] |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2014-10-25 : 15:48:54
|
[code]SELECT Year(DATEADD(mm,DATEDIFF(mm,0,fakdat),0)) AS YearNr,MONTH(DATEADD(mm,DATEDIFF(mm,0,fakdat),0)) AS MonthNr,dagbknr AS InvoiceType,MIN(faknr) AS InitialNr,MAX(faknr) AS FinalNr, COUNT(*) AS TotalRecordsFROM dbo.frhkrgWHERE fakdat >= DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0)AND fakdat < DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0)GROUP BY DATEDIFF(mm,0,fakdat),dagbknr ORDER BY DATEDIFF(mm,0,fakdat),dagbknr[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
|
|
|