mysql从同一个字段返回2个不同的列,但具有不同的条件

时间:2015-11-16 02:18:54

标签: mysql

如何从不同条件的相同字段返回2列,这是两个条件:

SELECT CITY,REGION,SALES FROM SALESREPS WHERE SALES < QUOTA;

SELECT CITY,REGION,SALES FROM SALESREPS WHERE SALES > QUOTA;

我的意思是说有些人说我只需要输入&#39; AND&#39;。那么我需要的是来自该示例的1行代码,它将返回2个不同的销售列。第一列将是销售额&lt;配额和另一列是销售&gt;配额。所有这些都来自同一张桌子。

3 个答案:

答案 0 :(得分:1)

您可以使用mySql if语句,如下所示:

SELECT 
    CITY,
    REGION,
    SALES,
    IF (SALES < QUOTA,SALES,null) as BELOW_QUOTA,
    IF (SALES > QUOTA,SALES,null) as ABOVE_QUOTA
    FROM SALESREPS;

答案 1 :(得分:0)

SELECT CITY,REGION,IF(SALES&lt; QUOTA,SALES)AS LessThanColumn,IF(Sales&gt; QUOTA,Sales)AS GreaterThanColumn FROM SALESREPS

答案 2 :(得分:0)

如果您只想要4列(CITYREGIONLOW_SALESHIGH_SALES),则每行只包含一个LOW_SALESHIGH_SALES有一个值(另一个为null),那么你可以:

select CITY
     , REGION
     , case when SALES < QUOTA then SALES end as LOW_SALES
     , case when SALES > QUOTA then SALES end as HIGH_SALES
  from SALESREPS;

SQL语句使用数据库不可知的语法,因此它可以在除MySQL之外的数据库上工作。

这也可以使用union

来完成
select CITY, REGION, SALES as LOW_SALES, null as HIGH_SALES
  from SALESREPS
 where SALES < QUOTA
union all
select CITY, REGION, null as LOW_SALES, SALES as HIGH_SALES
 from SALESREPS
 where SALES > QUOTA;

对我来说没有任何意义,例如那些有SALES = QUOTA的行?

现在,如果您想要CITY / REGION的总计,那对我来说更有意义(包括HIGH_SALES中的完全相等):

select CITY
     , REGION
     , sum(case when SALES < QUOTA then SALES else 0 end) as LOW_SALES
     , sum(case when SALES >= QUOTA then SALES else 0 end) as HIGH_SALES
  from SALESREPS
 group by CITY
        , REGION;

如果您只想要计数:

select CITY
     , REGION
     , sum(case when SALES < QUOTA then 1 else 0 end) as LOW_SALES
     , sum(case when SALES >= QUOTA then 1 else 0 end) as HIGH_SALES
  from SALESREPS
 group by CITY
        , REGION;