Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Count

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 MonthNr
FROM dbo.frhkrg
WHERE (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, TotalRecords
from (
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 rn
from @t
) q
where rn = 1
order by YearNr, MonthNr, InvoiceType desc
[/code]
Go to Top of Page

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 TotalRecords
FROM dbo.frhkrg
WHERE 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 MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -