[英]Aggregation while using count(distinct)
我有一個名為 public_report 的表,其中包含 50 列。 我想要一個特定列的計數(不同)以及所有列,因為我需要在 Tableau 中運行它
select count(distinct l.lead_key), l.*
from public_report l
group by l.lead_key
我在執行查詢時遇到此錯誤
嘗試執行查詢時出錯:[SQLState 42803] 錯誤:列“l.enquiry_key”必須出現在 GROUP BY 子句中或用於聚合函數中
我嘗試添加 l.enquiry_key 但它也拋出了其他列名。 任何人都可以建議大約有 50 列。
也試過這個
select t.lk, t.c, lp.*
from (select lead_key lk, count(distinct lead_key) c
from public_report
group by lead_key) t
join public_report lp
on lp.lead_key = t.lk
但這並沒有給我正確的計數。
該表有 8700000 個不同的 Lead_key 值。 但我得到 14565498 作為計數 d 值
請幫忙
也許相關子查詢是您想要的?
select p.*, (select count(*) from public_report p2
where p2.lead_key = p.lead_key)
from public_report p
如果您想知道不同的 Lead_key 的數量,您不應該對要聚合的同一行進行分組
select count(distinct l.lead_key)
from public_report l
如果您想要每個鍵的計數,則使用 group by ket 和 count(*)
select l.lead_key, count(*)
from public_report l
group by l.lead_key
如果你想要 count(distinct l.lead_key) 除了其他列,你可以使用交叉連接
select lp.*, t. my_count
from public_report lp
cross join (
select count(distinct l.lead_key) my_count
from public_report l
) t
如果您想將每個 Lead_key 的計數放在其他列之外,您可以使用 subwuery 與 group by 的內部連接
select lp.*, t.my_lk_count
from public_report lp
inner join (
select l.lead_key, count(*) my_lk_count
from public_report l
group by l.lead_key
) t ON t.lead_key = lp.lead_key
這是你想要的嗎?
select lp.*, t.count_distinct
from public_report lp cross join
(select count(distinct lead_key) as count_distinct
from public_report
) t;
或者,因為大多數數據庫都支持count(distinct)
作為窗口函數:
select pr.*, count(distinct lead_key) over () as count_distinct
from public_report pr
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.