簡體   English   中英

sql在am / n關系中計數多個列

[英]sql count multiple columns in a m/n relationship

我正在努力處理三個相關的表,在這些表中我想顯示使用特定代碼的域 數和地址數 我有三個表:

table_locations

ID | domain       | address             
======================================
 1 | example.com  | example.com/siteA   
 2 | example.com  | example.com/siteB   
 3 | example.com  | sub.example.com     
 4 | whatever.com | whatever.com 
 5 | foobar.com   | foobar.com/site123  
 6 | foobar.com   | foobar.com/site     

table_codes

ID | code        
==========
 1 | ABC 
 2 | DEF  

table_codes_locations

code_id | location_id        
=====================
 1      | 1 
 1      | 2    
 1      | 3
 1      | 4
 2      | 5 
 2      | 6 

我想得到的內容(編輯:將查詢限制為address ='example.com'時):

ID | code  | domaincount | addresses      
=====================================
 1 | ABC   |  2          | 3
 2 | DEF   |  1          | 2

這意味着代碼“ ABC”用於一個域(example.com)和三個子域; “ DEF”用於一個域和兩個子域

domaincount顯示使用代碼的域的數量,而地址顯示使用代碼的給定域的地址的數量。 我不確定是否僅用一條語句就能做到

您可以使用count(distinct)來做到這一點:

select c.code, count(distinct l.domain) as numdomains,
       count(l.address) as numaddress
from codes c left outer join
     code_locations cl
     on c.id = cl.code_id left outer join
     locations l
     on l.id = cl.location_id
group by c.code;

編輯:

也許:

select c.code, count(distinct l.domain) as numdomains,
       count(l.address) as numaddress,
       sum(case when l.address like '%example.com% then 1 else 0 end) as NumAddressExample
from codes c left outer join
     code_locations cl
     on c.id = cl.code_id left outer join
     locations l
     on l.id = cl.location_id
group by c.code;

暫無
暫無

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

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