我有两个给定结构的表:
表格1:
ST_Id ST_Name 1 xx 2 yy
表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
我希望逐月从mysql订单中获得结果.在我的php页面中,我有一个用于显示数据的表结构,如下所示
State December November September xx 300 1500 0 yy 0 200 0
除了这几个月,我还有一个排序链接,用于根据月份对金额进行排序.因此,当我单击对应于11月份的排序图像时,它应该根据该列中的金额顺序列出表格数据.如果我点击升序排序,它应该列出,如,
State December November September yy 0 200 0 xx 300 1500 0
我尝试了以下查询:
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
此查询返回如下所示的数据.
ST_Name SUM(AT.AT_Amt) xx 300 xx 1700
但预期的结果是:
ST_Name SUM(AT.AT_Amt) yy 200 xx 1500
有人可以帮我解决这个问题吗?提前致谢.
你可以这样做:
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;
一旦将数据导入PHP,您就可以使用JavaScript来使用TableSorter或类似的库进行客户端排序.这样排序不会导致重新查询数据库的费用.
您的数据结果将是:
+---------+----------+----------+-----------+ | st_name | December | November | September | +---------+----------+----------+-----------+ | xx | 300 | 1500 | 0 | | yy | 0 | 200 | 0 | +---------+----------+----------+-----------+
点击下面的链接查看正在运行的演示:
SQLFiddle
编辑:
根据您的评论,这是您需要的吗?
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
示例:http://sqlfiddle.com/#!9/51c7c/7用于演示
结果:
| st_name | Amount | |---------|--------| | yy | 200 | | xx | 1500 |