MySQL UNION ALL从Alias创建列

时间:2014-11-06 22:37:56

标签: mysql sql union-all

我有一个带有union的查询,它从3个不同的表中获取数据。查询工作正常,但我想要实现的是将KWH和Present Demand作为具有相应值的实际列,而不是用于标识引用的值类型的别名过滤器列。

I would like to have the following
name     kwh        Demand   date
meter1   10252.25   25.35    2014-11-06 

这里我附上MySQL查询。

SELECT
ds.name as KWH_Name,
ROUND(pv.pointValue,2) as KWH,
FROM_UNIXTIME(pv.ts/1000) as Date,
'KWH' as Filter

FROM 
mango.pointvalues as pv,
mango.datapoints as dp,
mango.datasources as ds

where
pv.dataPointId = dp.id and
FROM_UNIXTIME(pv.ts/1000) > '2014-10-31' and
dp.dataSourceId = ds.id and
ds.xid in ('DS_151181','DS_495799','DS_432821','DS_067251','DS_896060','DS_056870','DS_975807','DS_144197','DS_851933','DS_092150','DS_581587','DS_683881','DS_654410','DS_778982','DS_484407','DS_618254') and
dp.xid in ('DP_527107','DP_679864','DP_094433','DP_258167','DP_302281','DP_424331','DP_695840','DP_150558','DP_160298','DP_971876','DP_968565','DP_263818','DP_244594','DP_923944','DP_561553','DP_865672')

UNION ALL

SELECT
ds.name as KWH_Name,
ROUND(pv.pointValue,2) as PRESENT_DEMAND,
FROM_UNIXTIME(pv.ts/1000) as Date,
'PRESENT DEMAND' as Filter

FROM 
mango.pointvalues as pv,
mango.datapoints as dp,
mango.datasources as ds

where
pv.dataPointId = dp.id and
FROM_UNIXTIME(pv.ts/1000) > '2014-10-31' and
dp.dataSourceId = ds.id and
ds.xid in ('DS_151181','DS_495799','DS_432821','DS_067251','DS_896060','DS_056870','DS_975807','DS_144197','DS_851933','DS_092150','DS_581587','DS_683881','DS_654410','DS_778982','DS_484407','DS_618254') and
dp.xid in ('DP_156052','DP_330754','DP_785426','DP_803690','DP_948480','DP_463738','DP_970137','DP_464935','DP_522683','DP_143012','DP_840629','DP_166536','DP_271470','DP_272164','DP_828573','DP_221039')

1 个答案:

答案 0 :(得分:1)

dp.xid列表外,您的查询基本相同。您可以使用条件聚合执行所需操作:

SELECT ds.name as KWH_Name,
       FROM_UNIXTIME(pv.ts/1000) as Date,
       SUM(case when dp.xid in ('DP_527107','DP_679864','DP_094433','DP_258167','DP_302281','DP_424331','DP_695840','DP_150558','DP_160298','DP_971876','DP_968565','DP_263818','DP_244594','DP_923944','DP_561553','DP_865672')
                then pv.pointValue
           end) as KWH,
       SUM(case when dp.xid in ('DP_156052','DP_330754','DP_785426','DP_803690','DP_948480','DP_463738','DP_970137','DP_464935','DP_522683','DP_143012','DP_840629','DP_166536','DP_271470','DP_272164','DP_828573','DP_221039')
                then pv.pointValue
           end) as PresentDemand
FROM mango.pointvalues pv JOIN
     mango.datapoints dp
     ON pv.dataPointId = dp.id JOIN
     mango.datasources ds
     ON dp.dataSourceId = ds.id 
WHERE FROM_UNIXTIME(pv.ts/1000) > '2014-10-31' and
      ds.xid in ('DS_151181','DS_495799','DS_432821','DS_067251','DS_896060','DS_056870','DS_975807','DS_144197','DS_851933','DS_092150','DS_581587','DS_683881','DS_654410','DS_778982','DS_484407','DS_618254')
GROUP BY ds.name, FROM_UNIXTIME(pv.ts/1000);