2011-08-27 173 views
1

這裏對網站和SQL查詢一般都不熟悉,所以請原諒這裏的noobness。我希望創建一個返回3列(從單個表)的SQL查詢:多列/從哪裏查詢SQL查詢

  1. 另類 「Region__C」
  2. 「ID」 去哪兒 「ACTIVE__C」 是 「Y」
  3. 計數的計數「ID」的地方其中「ACTIVE__C」是「N」

下面是查詢將執行#1和#2或#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 

預先感謝任何幫助,任何人都可以提供!

回答

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 
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