这是我的查询
SELECT
pa.products_attributes_id,
pa.products_id,
pa.options_id
FROM products_attributes pa
LEFT JOIN products_description pd
ON pa.products_id = pd.products_id
AND pd.language_id = '1'
LEFT JOIN products_attributes_groups pag
ON pa.products_attributes_id = pag.products_attributes_id
WHERE pa.products_id = '109'
GROUP BY pa.products_attributes_id
ORDER BY pa.attribute_sort
正如您在上一栏options_id
中所见,有3个唯一的选项ID(即2,13和1)
我想要实现的是计算option_id列中唯一ID的数量。在上面的结果集中,查询应该返回3(因为有3个唯一的option_ids 2,13和1)。 如果此计数出现在包含结果集所有行的新temprary列中,我就不会有问题
P.S:我不想在获取数据时需要更改GROUP BY pa.products_attributes_id
编辑:使用(SELECT COUNT(DISTINCT options_id) FROM products_attributes ) AS options_id_count
结果集现在是12,这是错误的(它应该是3)
答案 0 :(得分:0)
您可以使用COUNT(DISTINCT options_id) as field_name
:)
答案 1 :(得分:0)
假设<REST_OF_YOUR_QUERY>
是以LEFT JOIN
SELECT
pa.products_attributes_id,
pa.products_id,
pa.options_id,
(
SELECT COUNT(DISTINCT options_id)
FROM products_attributes
<REST_OF_YOUR_QUERY>
) option_count
FROM products_attributes pa
<REST_OF_YOUR_QUERY>
答案 2 :(得分:0)
查询应该返回3
这只是options_id
products_attributes
中products_id
的明显统计数字109:
select count(distinct options_id)
from products_attributes
where products_id = 109;
答案 3 :(得分:0)
由于您必须对数据进行两次传递(一次提取结果,一次计算不同的option_id值),您可以将查询放入with中,然后只引用两次。 Oracle会将其优化为临时GTT,并且只读取一次源数据。
WITH d AS
(SELECT pa.products_attributes_id,
pa.products_id,
pa.options_id
FROM products_attributes pa
LEFT JOIN products_description pd
ON pa.products_id = pd.products_id
AND pd.language_id = '1'
LEFT JOIN products_attributes_groups pag
ON pa.products_attributes_id = pag.products_attributes_id
WHERE pa.products_id = '109'
GROUP BY pa.products_attributes_id
ORDER BY pa.attribute_sort)
SELECT d.*,
(SELECT COUNT(DISTINCT d.options_id)
FROM d)
FROM d;