Q
計數由
0
A
回答
0
這是一個奇怪的表結構和/或任務。你可能想考慮一下你的數據庫設計。反正...
select
num,
coalesce(agga.cnt, 0) as a,
coalesce(aggb.cnt, 0) as b,
coalesce(aggc.cnt, 0) as c,
coalesce(aggd.cnt, 0) as d
from (select a as num, count(*) as cnt from mytable group by a) agga
full outer join (select b as num, count(*) as cnt from mytable group by b) aggb using(num)
full outer join (select c as num, count(*) as cnt from mytable group by c) aggc using(num)
full outer join (select d as num, count(*) as cnt from mytable group by d) aggd using(num)
order by num;
1
使用UNPIVOT
然後PIVOT
:
的Oracle 11g R2架構設置:
CREATE TABLE table_name (a, b, c, d) AS
SELECT 1, 2, 1, 2 FROM DUAL UNION ALL
SELECT 1, 2, 2, 2 FROM DUAL UNION ALL
SELECT 2, 1, 3, 3 FROM DUAL UNION ALL
SELECT 3, 3, 2, 4 FROM DUAL UNION ALL
SELECT 4, 4, 2, 5 FROM DUAL UNION ALL
SELECT 5, 5, 5, 5 FROM DUAL;
查詢1:
SELECT *
FROM table_name
UNPIVOT(value FOR name IN (A, B, C, D))
PIVOT (COUNT(1) FOR name IN ('A' AS A, 'B' AS B, 'C' AS C, 'D' AS D))
| VALUE | A | B | C | D |
|-------|---|---|---|---|
| 1 | 2 | 1 | 1 | 0 |
| 2 | 1 | 2 | 3 | 2 |
| 4 | 1 | 1 | 0 | 1 |
| 5 | 1 | 1 | 1 | 2 |
| 3 | 1 | 1 | 1 | 1 |
1
with
inputs (a, b, c, d) as (
select 1, 2, 1, 2 from dual union all
select 1, 2, 2, 2 from dual union all
select 2, 1, 3, 3 from dual union all
select 3, 3, 2, 4 from dual union all
select 4, 4, 2, 5 from dual union all
select 5, 5, 5, 5 from dual
)
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select grade,
count(case when a = grade then 0 end) as a,
count(case when b = grade then 0 end) as b,
count(case when c = grade then 0 end) as c,
count(case when d = grade then 0 end) as d
from inputs cross join (select level as grade from dual connect by level <= 5)
group by grade
order by grade
;
GRADE A B C D
---------- ---------- ---------- ---------- ----------
1 2 1 1 0
2 1 2 3 2
3 1 1 1 1
4 1 1 0 1
5 1 1 1 2
注意:這是基本相同MT0的解決方案,但無論是unpivoting和旋轉都完成了「老辦法」(因爲他們以前做過PIVOT和UNPIVOT操作員是在Oracle 11.1中引入的)。
相關問題
- 1. 計數由
- 2. 計數由
- 3. 遍歷由計數
- 4. 貓鼬 - 由陣列元件組,計數和分類由計數
- 5. 選擇由計數,但不計
- 6. 獲得由最高計數
- 7. 查詢計數組由
- 8. MySQL的計數由於
- 9. 集團由主要計數
- 10. 計數由多個日期
- 11. 組由2列和計數
- 12. SQL Server CE計數組由
- 13. 計數由特定類
- 14. SQL計數誤差由2
- 15. SQL:計數()和組由
- 16. MySQL的計數,然後由該組數
- 17. Mysql-計數數據由列2
- 18. 左連接,總數和計數組由
- 19. 計劃 - 由0
- 20. 路由計算
- 21. 集團由數組元素的散列內,計算計數
- 22. MySQL的排序由重複計數
- 23. Grails的預測由集團和計數
- 24. 組由SQL找到最大計數
- 25. 計數由regexp_like返回的行
- 26. 數據庫設計問題由於量
- 27. 計數書面通過由GZIPOutputStream
- 28. 計數和組由多個列
- 29. 計數事件,查找由標題行
- 30. LINQ - 3子由與組選擇計數
您使用的是什麼RDBMS?請標記。另外,你到目前爲止嘗試過什麼?顯示你的努力.. –
請粘貼文本,而不是圖像。你有什麼嘗試,你卡在哪裏? –
我還沒有嘗試過很多,因爲我沒有真正的線索 – Nico