开发者

Multiple Columns/Where From SQL Query

New to the site, and SQL queries in general here, so forgive the noobness here. I'm looking to create a SQL query that returns 3 columns (from a single table):

  1. Distinct "Region__C"
  2. Count of "ID" Where "ACTIVE__C" is "Y"
  3. Count of "ID"开发者_如何学Python Where "ACTIVE__C" is "N"

Here's the query that would do #1 and #2 OR #3. Just not sure how to approach creating both column #2 and #3 in the same query:

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

Thanks in advance for any help that anyone can provide!


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


I think this will work:

 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜