[英]Count on UNION in Oracle
我有 3 個表,我需要從 UNION 計數大於 1 的 2 個表中獲取詳細信息。但也需要應用某些條件
Table A
id entity_id name category
1 45 abcd win_1
2 46 efgh win_2
3 47 efgh1 win_2
4 48 dfgh win_5
5 49 adfgh win_4
Table B
id product_id name parent_id
1 P123 asdf win_1
2 P234 adfgh win_4
Table 3 category_list
id cat_id name
1 win_1 Households
2 win_2 Outdoors
3 win_3 Mixed
4 win_4 Omni
現在我需要從表 A 和表 B 中獲得 UNION 的計數,其中 cat_id 的計數大於 1 和 Table A.name != Table B.name
我需要的結果是
p_id name cat_id
45 abcd win_1
P123 asdf win_1
46 efgh win_2
47 efgh1 win_2
win_5
被排除,因為計數為 1, win_4
應該被排除,因為表 A 和 B 中的名稱相同。
我已經用完了 Ideas,因為我對 Oracle 和 DB 比較陌生。感謝任何幫助。
我認為您可以使用exists
來確保兩個表中都存在 cat_id
select entity_id as p_id, name, category as cat_id
from table_a a
where exists (select null from table_b where a.category = table_b.parent_id)
union
select entity_id, name, parent_id
from table_b b
where exists (select null from table_a where b.parent_id = table_a.category)
我相信你正在尋找這樣的東西 -
Select T2.*
from
(Select category
from
(Select name, category from TableA
Union all
Select name, parent_id as category from TableB) t
group by category
having count(distinct name) > 1) T1
Join
(Select entity_id as Pid, name, category from TableA
Union
Select product_id as Pid, name, parent_id as category from TableB) T2
ON T1.category = T2.category;
你會試試這個代碼。 首先 CTE(通用表表達式) “list_union”獲取每個表的記錄,這些記錄具有不同的名稱,然后進行聯合。 使用第二個 CTE "list_cnt"計算類別,最終得到結果 cnt>1 與最后一個 select 語句如圖所示。
With
list_union AS (
SELECT
id,
----------
TO_CHAR(entity_id) entity_id,
----------
name,
category
FROM table_A a
WHERE NOT EXISTS(SELECT 1 FROM table_B b WHERE a.name=b.name)
----------
UNION ALL
----------
SELECT
id,
product_id,
name,
parent_id
FROM table_B b
WHERE NOT EXISTS(SELECT 1 FROM table_A a WHERE a.name=b.name)
)
,list_cnt AS (
SELECT
l.*,
----------
COUNT(*) over (PARTITION BY category) cnt
----------
FROM list_union l
)
SELECT
entity_id AS p_id,
name,
category AS cat_id
FROM list_cnt
WHERE cnt>1
ORDER BY cat_id ASC, p_id ASC
;
只需使用union all
和 window 函數:
select ab.*
from (select ab.*,
count(distinct name) over (partition by category) as cnt
from ((select a.* from a
) union all
(select b.* from b
)
) ab
) ab
where cnt > 1;
盡管您將問題描述為:
現在我需要從表 A 和表 B 中獲得 UNION 的計數,其中 cat_id 的計數大於 1 和 Table A.name != Table B.name
你似乎只是想cat_id
S作跨越兩個表不同的名字。 您的示例數據包括cat_id = 'win_2'
,它甚至不在第二個表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.