4

I have two tables with given structure :

Table 1:

ST_Id  ST_Name  
1       xx  
2       yy

Table 2 :

AT_Id   AT_Amt  ST_ID   Date

1       500      1     2015-11-17
2       1000     1     2015-11-15
3       300      1     2015-12-1
4       200      2     2015-11-2

I want to get results from mysql order by month. In my php page, I have a table structure for displaying data like shown below

State       December    November    September

xx          300         1500          0
yy           0          200           0

Along with these months, I have a sorting link for sorting the amounts based on month. So when I click the sorting image corresponding to the month November, it should list the table data according to the order of amount in that column. If I clicked for ascending sorting it should list like,

State       December    November    September

yy            0          200         0
xx            300        1500        0

I tried with following query :

SELECT ST.ST_Name,SUM(AT.AT_Amt)     
            FROM `Table2` AS AT 
            LEFT JOIN Table1 AS ST ON AT.ST_Id = ST.ST_Id  
             WHERE AT.Date BETWEEN '2015-04-01' AND '2015-12-31' GROUP BY MONTH( AT.Date) ORDER BY IF(MONTH(AT.Date) = 11 ,  SUM(AT.AT_Amt)  , MONTH( AT.Date)) ASC 

This query is returning data like shown below.

ST_Name   SUM(AT.AT_Amt)
xx        300
xx        1700

But the expected result is :

ST_Name   SUM(AT.AT_Amt)
yy        200
xx        1500

Can anyone please help me fix this? Thanks in advance.

Jenz
  • 8,280
  • 7
  • 44
  • 77

1 Answers1

5

You can do something like this:

SELECT
    st_name,
    SUM(CASE WHEN MONTH(dt) = 12 THEN at_amt ELSE 0 END) AS December,
    SUM(CASE WHEN MONTH(dt) = 11 THEN at_amt ELSE 0 END) AS November,
    SUM(CASE WHEN MONTH(dt) = 10 THEN at_amt ELSE 0 END) AS September
FROM table2
INNER JOIN table1 ON table1.st_id = table2.st_id
GROUP BY st_name;

Once you get data into PHP, you could just use JavaScript to do client-side sorting using TableSorter or similar library. That way sorting doesn't incur the expense of re-querying the database.

Result of your data will be:

+---------+----------+----------+-----------+
| st_name | December | November | September |
+---------+----------+----------+-----------+
| xx      |      300 |     1500 |         0 |
| yy      |        0 |      200 |         0 |
+---------+----------+----------+-----------+

Click the link below for a running demo:

SQLFiddle

EDIT:

Based on your comment, is this something you need?

SELECT 
  ST.ST_Name,
  SUM(AT.AT_Amt) as Amount
FROM `Table2` AS AT 
LEFT JOIN Table1 AS ST ON AT.ST_Id = ST.ST_Id  
WHERE AT.dt BETWEEN '2015-04-01' AND '2015-12-31' 
AND MONTH(AT.dt) = 11
GROUP BY ST.ST_Name
ORDER BY Amount

Example: http://sqlfiddle.com/#!9/51c7c/7 for demo

Result:

| st_name | Amount |
|---------|--------|
|      yy |    200 |
|      xx |   1500 |
zedfoxus
  • 35,121
  • 5
  • 64
  • 63