我有product
和agegroup
表。
我正在id
来自agegroup
表格的agegroup
和来自product
表格的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;
的比赛中加入这两个表格。
我正在使用的查询在这里;
{{1}}
但是,我的问题是,如果产品A在'0-3个月'中列出,而产品B在'3-6个月'中列出,则这两个产品不会在'0-24个月'中列出。
我想修改我的查询,以便产品A和B也在'0-24个月'中列出
答案 0 :(得分: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,您将完全消除案例。
答案 1 :(得分:0)
我不确定你为什么要选择这种情况。 最好使用 UNION运算符(这只是产品和年龄组表的联合)
FULL OUTER JOIN(连接两个表并从两个表中获取数据,即使两个表中都有NULL值。)