大家早上好。我无法使用union all语句将3个输出组合在一起。我的查询在下面,我得到一个错误,说ATTR无效。
想法?
Error report -
SQL Error: ORA-00904: "ATTR": invalid identifier
00904. 00000 - "%s: invalid identifier"
SELECT
"TOC_GENDER" as Attr_Type
,TOC_GENDER as Attr
,COUNT (DISTINCT CON_INDIVIDUAL_ID) AS UNIQ_INDIV_ID_CNT
,COUNT (DISTINCT TOC_DEALER_NO) AS UNIQ_DLR_CNT
FROM zeta.Customer_table
GROUP BY Attr_Type, attr
union all
SELECT
"TOC_HD_TARGET_SEGMENT" as Attr_Type
,TOC_HD_TARGET_SEGMENT as attr
,COUNT (DISTINCT CON_INDIVIDUAL_ID) AS UNIQ_INDIV_ID_CNT
,COUNT (DISTINCT TOC_DEALER_NO) AS UNIQ_DLR_CNT
FROM zeta.Customer_table
GROUP BY Attr_Type, attr
union all
SELECT
"TOL_POLK_COMPETITIVE_BRAND" as Attr_Type
,TOL_POLK_COMPETITIVE_BRAND as attr
,COUNT (DISTINCT CON_INDIVIDUAL_ID) AS UNIQ_INDIV_ID_CNT
,COUNT (DISTINCT TOC_DEALER_NO) AS UNIQ_DLR_CNT
FROM zeta.Customer_table
GROUP BY Attr_Type, attr
ORDER BY Attr_Type, attr;
答案 0 :(得分:3)
不要按列的别名来分组:
SELECT
"TOC_GENDER" as Attr_Type
,TOC_GENDER as Attr
,COUNT (DISTINCT CON_INDIVIDUAL_ID) AS UNIQ_INDIV_ID_CNT
,COUNT (DISTINCT TOC_DEALER_NO) AS UNIQ_DLR_CNT
FROM zeta.Customer_table
GROUP BY Attr_Type, attr
应该是
SELECT
"TOC_GENDER" as Attr_Type
,TOC_GENDER as Attr
,COUNT (DISTINCT CON_INDIVIDUAL_ID) AS UNIQ_INDIV_ID_CNT
,COUNT (DISTINCT TOC_DEALER_NO) AS UNIQ_DLR_CNT
FROM zeta.Customer_table
GROUP BY TOC_GENDER
答案 1 :(得分:0)
您无法在group by
中使用别名。将这些更改为group by TOC_GENDER
等。
此外,使用ORDER BY
UNION
可能会非常棘手(并且也无法使用别名)。使用当前select
子句将整个查询包装在外部ORDER BY
中,或将其更改为ORDER BY 1,2
。
要添加具有静态值的列,您需要使用单引号,而不是双引号。单引号用于划分字符串,而双引号用于划分标识符(例如表名或列名)。
由于具有静态字符串的列在整个结果集中具有单个值,因此不需要将其包含在GROUP BY
子句中。