Search code examples
javasqlucanaccess

SQL Pivot table for monthly aggregate amount


I've not much experience in sql.In my little java program using ucanaccess library I was able to perform some simple queries after creating a simple table (named ReportSales). The table is:

ID  DATE            PRODUCT     SALES       FEES
1   2014-10-02      productA    10.000      100
2   2014-09-02      productC    12.000      240
3   2014-09-02      productA    8.000        80
4   2014-11-02      productB    7.000       105
5   2014-08-02      productB    6.000        90
..  ..........      ........    ......      ....
..  ..........      ........    ......      ....

The last task is to create a pivot table in which I would insert the monthly sales per product. Something like:

PRODUCT     AUG         SEP         OCT      NOV
productA    0         8.000      10.000        0
productB    6000          0           0     7000
productC    0        12.000           0        0

And another pivot for monthly fees

My (wrong) attempt is:

SELECT [8] as AUG, [9] as SEP, [10] as OCT, [11] as NOV
FROM
(SELECT SALES,MONTH(DATE) 
    FROM ReportSales) AS tmp
PIVOT
(
SUM(SALES)
FOR MONTH(DATE) IN ([8], [9], [10], [11])
) AS PivotTable

Does anyone can help me? Thanks in advance


Solution

  • UCanAccess supports Pivot queries, only if they are built in Access, so you have firstly to create a crosstab query using the Access IDE. Or you may simply create a new query in Access entering directly the following SQL:

    TRANSFORM sum(ReportSales.sales) AS SalesCount
    SELECT ReportSales.product
    FROM ReportSales
    GROUP BY ReportSales.product
    PIVOT Format([date],"mmm");
    

    Then assuming that you saved the query as query1, you have just to execute, with UCanAccess:

    Select * from query1;