Subject | RE: [firebird-support] Advice on following SQL string |
---|---|
Author | Svein Erling Tysvær |
Post date | 2011-06-22T06:46:06Z |
>What I am trying to do is get a weekly summary of all the sales for eachYour desired report didn't format quite properly, I guess this is the output you want:
>item PER DAY
BARCODENUMBER POSDESCRIPTION D_20110612 D_20110614
401440 M&M PEANUT BUTTER 1 2
02800082226 LAFFY TAFFY - CHERRY 1
782640 A & W CREAM SODA 1
The one thing that makes this very difficult, is that SQL is no good at turning field values into column headings the way you can easily do with pivot tables. One simple option for you to consider, after changing field types as Norman says, is to do a pretty simple select similar to what Alan suggests and then use pivot tables in Excel (or similar) to get things formatted the way you want.
If you prefer to get a weekly summary only using SQL, you would need a bit more complicated SQL:
WITH Barcodes(BarcodeNumber, PosDescription)
as
(SELECT DISTINCT BarcodeNumber, PosDescription
FROM TableInAndrewsDatabase
WHERE TradeDate BETWEEN CURRENT_DATE - 6 and CURRENT_DATE),
SumSold(BarcodeNumber, TradeDate, QtySold)
as
(SELECT BarcodeNumber, TradeDate, sum(QtySold)
FROM TableInAndrewsDatabase
WHERE TradeDate BETWEEN CURRENT_DATE - 6 and CURRENT_DATE
GROUP BY 1, 2)
SELECT B.BarcodeNumber, B.PosDescription, S1.QtySold as D1, S2.QtySold as D2, S3.QtySold as D3, S4.QtySold as D4, S5.QtySold as D5, S6.QtySold as D6, S7.QtySold as D7
FROM Barcodes B
LEFT JOIN SumSold S1
ON B.BarcodeNumber = S1.BarcodeNumber
AND S1.TradeDate = CURRENT_DATE - 6
LEFT JOIN SumSold S2
ON B.BarcodeNumber = S2.BarcodeNumber
AND S2.TradeDate = CURRENT_DATE - 5
LEFT JOIN SumSold S3
ON B.BarcodeNumber = S3.BarcodeNumber
AND S3.TradeDate = CURRENT_DATE - 4
LEFT JOIN SumSold S4
ON B.BarcodeNumber = S4.BarcodeNumber
AND S4.TradeDate = CURRENT_DATE - 3
LEFT JOIN SumSold S5
ON B.BarcodeNumber = S5.BarcodeNumber
AND S5.TradeDate = CURRENT_DATE - 2
LEFT JOIN SumSold S6
ON B.BarcodeNumber = S6.BarcodeNumber
AND S6.TradeDate = CURRENT_DATE - 1
LEFT JOIN SumSold S7
ON B.BarcodeNumber = S7.BarcodeNumber
AND S7.TradeDate = CURRENT_DATE
I've made some assumptions:
1) TradeDate is defined as Date, not TimeStamp
2) QtySold is defined as some kind of number
3) There's only one PosDescription for each BarcodeNumber
4) You want the report for the last week until today - if you want other time periods, just replace CURRENT_DATE
What I do not know how to do (through SQL, you could easily write a simple program to achieve the same thing), is to get the actual dates as headers rather than D1, D2 etc.
HTH,
Set