2012-04-24 56 views
0

我有productagegroup表。SQL案例當條件超過

我加入了這兩個表idagegroup表和agegroupproduct表中匹配。

我正在使用的查詢是在這裏;

WITH CTE_AgeGroup AS                    
       (
       SELECT p.agegroup, 
         CASE 
          WHEN AgeFromMonths >=0 AND AgeToMonths <= 24 
           THEN 
            CASE 
              WHEN AgeFromMonths >=0 AND AgeToMonths <= 3 THEN '0-3 Months' 
              WHEN AgeFromMonths >=3 AND AgeToMonths <= 6 THEN '3-6 Months' 
              WHEN AgeFromMonths >=6 AND AgeToMonths <= 9 THEN '6-9 Months' 
              WHEN AgeFromMonths >=9 AND AgeToMonths <= 12 THEN '9-12 Months' 
              WHEN AgeFromMonths >=12 AND AgeToMonths <= 18 THEN '12-18 Months' 
              WHEN AgeFromMonths >=18 AND AgeToMonths <= 24 THEN '18-24 Months' 
              END 
          END as 'age' 
       FROM agegroup a inner join product p on 
       a.id= p.agegroup 

       ), 
        CTE_AgeGroupResultSet AS 
       (
        select 
         Age, Count(*) AS CountAge from CTE_AgeGroup group by Age 
        ) 
       select * from CTE_AgeGroupResultSet order by age; 

然而,我的問題是,如果產品A是在「0-3個月上市,而產品B上市嗡」3〜6個月,這兩款產品都沒有獲得「0-上市24個月。

我想修改我的查詢,使產品A和B也獲得「0-24個月

任何意見上市,將不勝感激!

回答

0

我不知道你爲什麼要去這個案件的功能。 這將是更好地使用 UNION操作(這只是需要雙方的聯合產品和agegroup表)

FULL OUTER JOIN(連接兩個表並從兩個表中獲取數據,即使有兩個NULL值。表)

+0

因爲when語句中使用的標籤是我需要的靜態過濾器,所以我沒有提供case語句。這就是爲什麼。 – user1352864 2012-04-24 06:21:48

1

你可能會在小組使用with rollup獲得盛大數:

WITH CTE_AgeGroup AS 
(
    SELECT p.agegroup, 
      CASE WHEN AgeFromMonths >=0 AND AgeToMonths <= 24 
       THEN CASE WHEN AgeFromMonths >=0 AND AgeToMonths <= 3 
          THEN '0-3 Months' 
          WHEN AgeFromMonths >=3 AND AgeToMonths <= 6 
          THEN '3-6 Months' 
          WHEN AgeFromMonths >=6 AND AgeToMonths <= 9 
          THEN '6-9 Months' 
          WHEN AgeFromMonths >=9 AND AgeToMonths <= 12 
          THEN '9-12 Months' 
          WHEN AgeFromMonths >=12 AND AgeToMonths <= 18 
          THEN '12-18 Months' 
          WHEN AgeFromMonths >=18 AND AgeToMonths <= 24 
          THEN '18-24 Months' 
         END 
      END as 'age' 
    FROM agegroup a 
     inner join product p 
      on a.id= p.agegroup 
), 
CTE_AgeGroupResultSet AS 
(
    select case when grouping (Age) = 1 then '0-24' else Age end Age, 
      Count(*) AS CountAge 
     from CTE_AgeGroup 
    group by Age WITH ROLLUP 
) 
select * 
    from CTE_AgeGroupResultSet 
order by age; 

另外,如果你增加一個VARCHAR列agegroup含組描述,你會完全消除的情況下。