网站的新手,以及一般的SQL查询,请原谅这里的noobness。我正在寻找创建一个返回3列(从单个表)的SQL查询:
这是将执行#1和#2 OR#3的查询。只是不确定如何在同一个查询中创建第2列和第3列:
SELECT DISTINCT SCHEMA.CONTACT.REGION__C AS "Region",COUNT(SCHEMA.CONTACT.ID) AS "Active Contacts"
FROM SCHEMA.CONTACT
WHERE SCHEMA.CONTACT.ACTIVE__C = 'Y' AND SCHEMA.CONTACT.REGION__C != 'Unknown'
GROUP BY SCHEMA.CONTACT.REGION__C
提前感谢任何人都可以提供的任何帮助!
答案 0 :(得分:2)
SELECT SCHEMA.CONTACT.REGION__C ,
COUNT(CASE WHEN SCHEMA.CONTACT.ACTIVE__C = 'Y' THEN 1
END) AS Y ,
COUNT(CASE WHEN SCHEMA.CONTACT.ACTIVE__C = 'N' THEN 1
END) AS N
FROM SCHEMA.CONTACT
WHERE SCHEMA.CONTACT.ACTIVE__C IN ( 'N', 'Y' ) AND
SCHEMA.CONTACT.REGION__C != 'Unknown'
GROUP BY SCHEMA.CONTACT.REGION__C
答案 1 :(得分:2)
我认为这会奏效:
SELECT DISTINCT SCHEMA.CONTACT.REGION__C AS "Region",
sum(case ACTIVE__C when 'Y' then 1 else 0 end) as "CountActive",
sum(case ACTIVE__C when 'N' then 1 else 0 end) as "CountInactive",
COUNT(SCHEMA.CONTACT.ID) AS "Active Contacts"
FROM SCHEMA.CONTACT
WHERE SCHEMA.CONTACT.REGION__C != 'Unknown'
GROUP BY SCHEMA.CONTACT.REGION__C