Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate and summarize data

I have the following:

declare @PrintJob TABLE (
  PageNumber Int,
  Copies Int
)

INSERT INTO @PrintJob(PageNumber,Copies) VALUES(1,100)
INSERT INTO @PrintJob(PageNumber,Copies) VALUES(2,100)
INSERT INTO @PrintJob(PageNumber,Copies) VALUES(3,100)
INSERT INTO @PrintJob(PageNumber,Copies) VALUES(4,100)
INSERT INTO @PrintJob(PageNumber,Copies) VALUES(5,50)
INSERT INTO @PrintJob(PageNumber,Copies) VALUES(6,25)

SELECT * FROM @PrintJob

Q: Is there a way to produce the following output in Microsoft SQL Server 2005?

Pages 1-4 = 100 Copies, 5-5 = 50 Copies, 6-6 = 25 Copies
like image 868
Phillip Senn Avatar asked Jul 03 '26 17:07

Phillip Senn


1 Answers

Assuming gaps can not occur, use:

SELECT CAST(MIN(pj.pagenumber) AS VARCHAR(max)) +'-'+ CAST(MAX(pj.pagenumber) AS VARCHAR(max)) +' = '+ CAST(pj.copies AS VARCHAR(max)) +' Copies' AS pages
  FROM PRINTJOB pj
GROUP BY pj.copies
ORDER BY pj.copies DESC

...will give you:

pages
-------
1-4 = 100 Copies
5-5 = 50 Copies
6-6 = 25 Copies
like image 110
OMG Ponies Avatar answered Jul 06 '26 08:07

OMG Ponies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!