有兩張桌子。表A具有以下結構
| ID | 旗幟 | 姓名 |
|---|---|---|
| 1X | 1 | 是 |
| 2年 | 0 | 空值 |
| 3Z | 1 | 空值 |
| 4A | 1 | 是 |
表B具有以下結構
| 出價 | 城市 | 狀態 |
|---|---|---|
| 1X | 是 | 空值 |
| 2年 | 空值 | 空值 |
| 3Z | 空值 | 是 |
| 4A | 是 | 是 |
我想獲取所有 ID 的計數以及在任何列(名稱、城市、州)中為 Null 的 ID 計數,例如,從上面的表格中,只有 ID 4A 在所有三列中都具有非空值跨越兩個表,所以輸出應該像
| 總數 | id 為空 | 百分比缺失 |
|---|---|---|
| 4 | 3 | 0.75% |
Total_count 為 4,因為總共有四個 ID,具有 NULL 的 ID 為 3,因為有 3 個 ID 在三列(即名稱、城市、州)中的任何一個中為空,而缺少的百分比只是 ID 為空 / Total_Count .
我嘗試使用以下幾行的查詢
select (count/total) * 100 pct, count,total
from (select sum(count) count
from(select count(*) count from tableA T1
where T1.name is null
union all
select count(*) count from tableA T1
join tableB T2 on T1.ID = T2.B_ID
where T2.city is null
union all
select count(*) count from tableA T1
join tableB T2 on T1.ID = T2.B_ID
where T2.state is null)),
select count(ID) total from tableA);
但是查詢沒有回傳所需的輸出,你能給我建議一個更好的方法嗎?謝謝你
uj5u.com熱心網友回復:
使用條件聚合:
SELECT COUNT(*) Total_Count,
COUNT(CASE WHEN t1.Name IS NULL OR t2.City IS NULL OR t2.State IS NULL THEN 1 END) Ids_having_null,
AVG(CASE WHEN COALESCE(t1.Name, t2.City, t2.State) IS NOT NULL THEN 1 ELSE 0 END) Percentage_missing
FROM Table1 t1 INNER JOIN Table2 t2
ON t2.B_ID = t1.ID;
請參閱演示。
uj5u.com熱心網友回復:
如果您不知道任一表是否包含所有 ID?
然后我建議full join在子查詢中使用一些條件聚合。
例如:
select Total as "Total_Count" , TotalMissing as "Ids having null" , (TotalMissing / Total)*100||'%' as "Percentage missing" from ( select count(distinct coalesce(a.ID, b.B_ID)) as Total , count(distinct case when a.name is null or b.city is null or b.state is null then coalesce(a.ID, b.B_ID) end) as TotalMissing from TableA a full outer join TableB b on a.ID = b.B_ID ) qTotal_Count | id 為空 | 百分比缺失 ----------: | --------------: | :----------------- 4 | 3 | 75%
db<>在這里擺弄
uj5u.com熱心網友回復:
試試這個 - >
select total_count, (total_count - cn) as ids_having_null,
(total_count - cn) *100 / total_count as Percentage_missing
FROM
(select count(t1.ID) as cn , t1.total_count
FROM ( select ID,Name, sum(tmp_col) over ( order by tmp_col) as total_count from (select ID,Name, 1 as tmp_col from tableA ) ) t1
JOIN TableB t2
ON t1.ID = t2.B_ID
WHERE t1.Name is not null and t2.City is not null and t2.State is not null );
根據您對百分比或比率的要求,您可以更改 Percentage_missing 列的邏輯
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/362591.html
上一篇:我無法將資料轉換為所需的形式
