如何使用COUNT和WHERE MySQL查询多个colums结合
问题描述:
所以我想通了如何生成一个报告,其中将数项基于WHERE条件一样每个月:如何使用COUNT和WHERE MySQL查询多个colums结合
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个可能的值买入和卖出。
所以我想另一列添加到结果,这样它看起来像
YEAR|MONTH|BUY_RESULT|SELL_RESULT
我怎样才能在MySQL中建立另一列???
我已经试过UNION但是这增加了卖出的结果,以结果表的末尾,不创建额外的列。
那么,如何创建使用WHERE子句,从而导致一个额外的列=“卖”被旁边的现有列,其中RESULT =“买入”添加?????
谢谢!!!!!
答
使用条件汇总:
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`));
答
一个简单的方法来完成,这是使用子查询:
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))
也许IF - THAN,看看[这里](HTTP:/ /dev.mysql.com/doc/refman/5.0/en/if.html) – skobaljic 2014-12-05 00:09:36
只是看到CASE ... – Strawberry 2014-12-05 00:17:53