簡體   English   中英

計算來自SQL中兩列的不同值的計數

[英]Counting the count of distinct values from two columns in sql

我在數據庫中有一個表,其中有相應的主鍵值。 我想計算兩列中的不同值。

我已經知道一種使用全部合並,然后在結果表上應用groupby的方法。

Select Id,Brand1
into #Temp
from data
union all
Select Id,Brand2
from data

Select ID,Count(Distinct Brand1)
from #Temp
group by ID

我們也可以只使用臨時表在大查詢中執行相同的操作。

樣品表

ID  Brand1  Brand2
1    A       B
1    B       C
2    D       A
2    A       D

結果表

ID  Distinct_Count_Brand
1    3
2    2

如您在此列中看到的那樣Distinct_count_Brand它從兩個列Brand1和Brand2中計算Brand的唯一計數。

我已經知道一種方法(基本上沒有支配性),但是想知道是否還有其他方法可以計算兩列中的唯一值。

我不知道BigQuery的怪癖,但也許您可以內聯聯合查詢:

SELECT ID, COUNT(DISTINCT Brand)
FROM
(
    SELECT ID, Brand1 AS Brand FROM data
    UNION ALL
    SELECT ID, Brand2 FROM data
) t
GROUP BY ID;

在SQL Server中,我將使用:

Select b.id, count(distinct b.brand)
from data d cross apply
     (values (id, brand1), (id, brand2)) b(id, brand)
group by b.id;

是db <>小提琴。

在BigQuery中,等效項表示為:

select t.id, count(distinct brand)
from t cross join
     unnest(array[brand1, brand2]) brand
group by t.id;

這是一個BQ查詢,證明它可以工作:

with t as (
      select 1 as id, 'A' as brand1, 'B' as brand2 union all
      select 1, 'B', 'C' union all
      select 2, 'D', 'A' union all
      select 2, 'A', 'D'
     )
select t.id, count(distinct brand)
from t cross join
     unnest(array[brand1, brand2]) brand
group by t.id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM