如何从不同条件的相同字段返回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;配额。所有这些都来自同一张桌子。
答案 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列(CITY
,REGION
,LOW_SALES
,HIGH_SALES
),则每行只包含一个LOW_SALES
和HIGH_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;