如何在使用COUNT和WHERE的MYSQL查询中组合多个列

时间:2014-12-05 00:07:33

标签: mysql

所以我已经想出如何生成一个报告,根据WHERE标准计算每个月的项目:

  SELECT
  Year(FROM_UNIXTIME(`tTime1`)) as YEAR,
  Month(FROM_UNIXTIME(`tTime1`)) as MONTH,
  Count(*) As BUY_RESULT 
  FROM zupsbackup
  WHERE Result='BUY' AND tPeriod='60' 
  GROUP BY Year(FROM_UNIXTIME(`tTime1`)), Month(FROM_UNIXTIME(`tTime1`))

这会产生表格结果,如

YEAR|MONTH|BUY_RESULT

但是我的结果列有2个可能的值BUY和SELL。

所以我想在结果中添加另一列,使其看起来像

YEAR|MONTH|BUY_RESULT|SELL_RESULT

如何在MYSQL中创建另一列???

我尝试过UNION但是这会将SELL结果添加到结果表的末尾,并且不会创建额外的列。

那么如何使用WHERE子句创建一个额外的列,以便在现有列旁边添加RESULT ='SELL',其中RESULT ='BUY'?????

谢谢!!!!!

2 个答案:

答案 0 :(得分:4)

使用条件聚合:

SELECT Year(FROM_UNIXTIME(`tTime1`)) as YEAR, Month(FROM_UNIXTIME(`tTime1`)) as MONTH,
       SUM(Result = 'BUY') As BUY_RESULT, SUM(Result = 'SELL') as SELL_RESULT
FROM zupsbackup
WHERE tPeriod = '60' 
GROUP BY Year(FROM_UNIXTIME(`tTime1`)), Month(FROM_UNIXTIME(`tTime1`));

答案 1 :(得分:0)

实现此目的的一种简单方法是使用子查询:

SELECT 
  Year(FROM_UNIXTIME(tTime1)) as YEAR, 
  Month(FROM_UNIXTIME(tTime1)) as MONTH, 
  Count(*) As BUY_RESULT, 
  (
    SELECT 
      COUNT(sub.*) 
    FROM 
      zupsbackup AS sub 
    WHERE 
      sub.Result = 'SELL' and 
      sub.tPeriod = '60' AND 
      Year(FROM_UNIXTIME(sub.tTime1)) = YEAR AND 
      Month(FROM_UNIXTIME(tTime1)) = MONTH
  ) AS SELL_RESULT
FROM 
  zupsbackup 
WHERE 
  Result='BUY' AND 
  tPeriod='60' 
GROUP BY 
  Year(FROM_UNIXTIME(tTime1)), 
  Month(FROM_UNIXTIME(tTime1))