如何GROUP_CONCAT这个查询

时间:2016-02-24 16:15:28

标签: mysql sql

我有疑问。

SELECT fdl.fdlDate,t.tankName,SUM(fdl.fdlMeter-lfdl.fdlMeter) AS fdlMeter ,(SELECT IFNULL(SUM(fdtCapa),0) FROM `fueldisptest` WHERE fdtDate = fdl.fdlDate AND compID = "DDY") AS fdtCapa
FROM `tanks` AS t
INNER JOIN `fueldisps` AS fd ON fd.tankID = t.tankID
INNER JOIN `fueldisplogs` AS fdl ON fdl.fuelDispID = fd.fuelDispID 
INNER JOIN `fueldisplogs` AS lfdl ON lfdl.fuelDispID = fd.fuelDispID AND lfdl.fdlDate = SUBDATE(fdl.fdlDate,1)
WHERE  (fdl.fdlDate BETWEEN "2016-01-01" AND "2016-01-31")
AND (lfdl.fdlDate BETWEEN "2015-12-31" AND "2016-01-30")
AND t.compID = "DDY" AND fd.compID = "DDY" AND fdl.compID = "DDY" AND lfdl.compID = "DDY"
GROUP BY fdl.fdlDate,t.tankID
ORDER BY fdl.fdlDate,t.tankID,fd.fuelDispID
LIMIT 0,100

它会给出这样的结果。

fdlDate    |  tankName    |  fdlMeter     |  fdtCapa  
-----------------------------------------------------
2016-01-01 | T1           | 100.00        | 0
2016-01-01 | T2           | 200.00        | 0
2016-01-01 | T3           | 300.00        | 0
2016-01-01 | T4           | 400.00        | 0
2016-01-02 | T1           | 200.00        | 0
2016-01-02 | T2           | 300.00        | 0
2016-01-02 | T3           | 400.00        | 0
2016-01-02 | T4           | 500.00        | 0
...

但我想使用GROUP_CONCAT来制作这样的结果。

fdlDate    |  fdlMeter                      |  fdtCapa  
----------------------------------------------------------------------
2016-01-01 | 100.00,200.00,300.00,400.00    | 0
2016-01-02 | 200.00,300.00,400.00,500.00    | 0
...

如何编辑我的查询以获得此结果? 谢谢。

1 个答案:

答案 0 :(得分:1)

您可以在结果

之上添加Group_Concat

试试这个

SELECT fdlDate,
       group_concat(lfdlMeter order by tankName  separator ',') as fdlMeter,      
       fdtCapa
FROM   (SELECT fdl.fdlDate,
               t.tankName,
               Sum(fdl.fdlMeter - lfdl.fdlMeter) AS lfdlMeter,
               (SELECT Ifnull(Sum(fdtCapa), 0)
                FROM   fueldisptest
                WHERE  fdtDate = fdl.fdlDate
                       AND compID = "DDY")       AS fdtCapa
        FROM   tanks AS t
               INNER JOIN fueldisps AS fd
                       ON fd.tankID = t.tankID
               INNER JOIN fueldisplogs AS fdl
                       ON fdl.fuelDispID = fd.fuelDispID
               INNER JOIN fueldisplogs AS lfdl
                       ON lfdl.fuelDispID = fd.fuelDispID
                          AND lfdl.fdlDate = Subdate(fdl.fdlDate, 1)
        WHERE  ( fdl.fdlDate BETWEEN "2016-01-01" AND "2016-01-31" )
               AND ( lfdl.fdlDate BETWEEN "2015-12-31" AND "2016-01-30" )
               AND t.compID = "DDY"
               AND fd.compID = "DDY"
               AND fdl.compID = "DDY"
               AND lfdl.compID = "DDY"
        GROUP  BY fdl.fdlDate,
                  t.tankID
        ORDER  BY fdl.fdlDate,
                  t.tankID,
                  fd.fuelDispID) s
GROUP  BY fdlDate,
          fdtCapa 
LIMIT 0,100