Teradata 行到列(需要合并双倍行数)
Teradata Rows to Columns (Need to Merge Doubled Row Count)
我有一个查询 运行 如下 -
SELECT
item1,
item2,
item3,
CASE WHEN item4 = 'type A' THEN COUNT(DISTINCT field) END AS dcount_field_A,
CASE WHEN item4 = 'type B' THEN COUNT(DISTINCT field) END AS dcount_field_B,
FROM table
GROUP BY
item1
item2
item3
item4
我的输出是:
Item1
Item2
Item 3
dcount_field_B
dcount_field_A
Item1Value1
Item2Value1
Item3Value1
NULL
1234
Item1Value1
Item2Value1
Item3Value1
1234
NULL
但我需要合并这些行,例如:
Item1
Item2
Item 3
dcount_field_B
dcount_field_A
Item1Value1
Item2Value1
Item3Value1
1234
1234
其他尝试调整:
- 从组中删除项目 4 给我一个错误 "Selected
非聚合值必须是关联组的一部分。"
- 我的 teradata 版本没有 PIVOT 选项
- 我也试过
的子查询
(SELECT
COUNT(DISTINCT(CASE WHEN item4 = 'type A' THEN field END)) AS dcount_field_A,
COUNT(DISTINCT(CASE WHEN item4 = 'type B' THEN field END)) AS dcount_field_B
FROM table
GROUP BY item4),
and I get the error "Too many expressions in the select list of a subquery."
您需要条件聚合。 count(distinct)
看起来像:
SELECT item1, item2, item3,
COUNT(DISTINCT CASE WHEN item4 = 'type A' THEN field END) AS dcount_field_A,
COUNT(DISTINCT CASE WHEN item4 = 'type B' THEN field END) AS dcount_field_B,
FROM table
GROUP BY item1, item2, item3;
我有一个查询 运行 如下 -
SELECT
item1,
item2,
item3,
CASE WHEN item4 = 'type A' THEN COUNT(DISTINCT field) END AS dcount_field_A,
CASE WHEN item4 = 'type B' THEN COUNT(DISTINCT field) END AS dcount_field_B,
FROM table
GROUP BY
item1
item2
item3
item4
我的输出是:
Item1 | Item2 | Item 3 | dcount_field_B | dcount_field_A |
---|---|---|---|---|
Item1Value1 | Item2Value1 | Item3Value1 | NULL | 1234 |
Item1Value1 | Item2Value1 | Item3Value1 | 1234 | NULL |
但我需要合并这些行,例如:
Item1 | Item2 | Item 3 | dcount_field_B | dcount_field_A |
---|---|---|---|---|
Item1Value1 | Item2Value1 | Item3Value1 | 1234 | 1234 |
其他尝试调整:
- 从组中删除项目 4 给我一个错误 "Selected 非聚合值必须是关联组的一部分。"
- 我的 teradata 版本没有 PIVOT 选项
- 我也试过 的子查询
(SELECT
COUNT(DISTINCT(CASE WHEN item4 = 'type A' THEN field END)) AS dcount_field_A,
COUNT(DISTINCT(CASE WHEN item4 = 'type B' THEN field END)) AS dcount_field_B
FROM table
GROUP BY item4),
and I get the error "Too many expressions in the select list of a subquery."
您需要条件聚合。 count(distinct)
看起来像:
SELECT item1, item2, item3,
COUNT(DISTINCT CASE WHEN item4 = 'type A' THEN field END) AS dcount_field_A,
COUNT(DISTINCT CASE WHEN item4 = 'type B' THEN field END) AS dcount_field_B,
FROM table
GROUP BY item1, item2, item3;