MySQL Union 2选择1个表并输出2列

时间:2012-12-13 23:49:49

标签: mysql group-by union

我目前有1个表和2个嵌套选择,我想将两个嵌套选择结合在一起,我希望结果集为每个结果集显示两个不同的列(每个嵌套选择一列)。 IE三列总共t_stamp,R02AO11,R03AO11。我已经在这几天敲打我的头了,任何可以提供帮助的人都会非常感激。我找到了这个例子Using SELECT UNION and returning output of two columns from one table,这对我来说没有意义 - 也许有点过头了。希望重新发布不是太多。再次感谢。 =)

Select t_stamp,
MIN(R02AO11) 
FROM
( 
SELECT 
    t_stamp,
    R02AO11
FROM 
    tag_history 
WHERE 
    from_unixtime(floor(unix_timestamp(t_stamp)/60)*60) BETWEEN '2012-11-01                                                                                          00:00:00' AND '2012-11-30 23:59:59' 
    AND (R02AO11 IS NOT NULL AND R02AO11 > 0) 
) AS min_tag_history
GROUP BY LEFT(t_stamp, 10)
UNION ## UNION ALL 
Select t_stamp, 
MIN(R03AO11) 
FROM
( 
SELECT 
    t_stamp,
    R03AO11
FROM 
    tag_history 
WHERE 
    from_unixtime(floor(unix_timestamp(t_stamp)/60)*60) BETWEEN '2012-11-01 00:00:00' AND '2012-11-30 23:59:59' 
    AND (R03AO11 IS NOT NULL AND R03AO11 > 0) 
) AS min_tag_history
GROUP BY LEFT(t_stamp, 10)
ORDER BY t_stamp

1 个答案:

答案 0 :(得分:0)

你是在思考这个还是我错过了什么?

SELECT 
    t_stamp,
    MIN(CASE WHEN R02AO11 = 0 THEN NULL ELSE R02AO11 END),
    MIN(CASE WHEN R03A011 = 0 THEN NULL ELSE R03A011 END)
FROM 
    tag_history 
WHERE 
    from_unixtime(floor(unix_timestamp(t_stamp)/60)*60) BETWEEN '2012-11-01                                                                                          00:00:00' AND '2012-11-30 23:59:59' 
GROUP BY LEFT(t_stamp, 10)