[英]SQL Count first occurrence
我的原始數據庫如下所示:
TYPE CONTRACT_ID
a 101011
c 101012
b 101011
b 101012
a 101011-1
c 101012
我試圖獲取按類型分組的數據,並計算唯一的CONTRACT_ID,但是有些合同有分包合同,例如101011有分包合同101011-1。 所有這些都必須算作一份合同。
我嘗試了與眾不同的方法,但由於部分轉包合同仍被視為唯一主菜,因此只能部分起作用。
SELECT TYPE, count(distinct CONTRACT_ID) as countocc
FROM db_address
group by TYPE
我期望這樣的輸出:
TYPE countocc
a 1
b 2
c 1
如何完全忽略分包合同? 當您擁有子合同時,您似乎擁有父合同:
SELECT TYPE, count(distinct CONTRACT_ID) as countocc
FROM db_address
WHERE CONTRACT_ID NOT LIKE '%-%'
GROUP BY TYPE;
使用CASE
語句僅計算'-'
(如果存在)之前的contract_id
部分:
select
type,
count(distinct
case
when contract_id like '%-%' then
substring(contract_id, 1, instr(contract_id, '-') - 1)
else contract_id
end
) counter
from db_address
group by type
這涵蓋了分包合同在表中但主合同不在表中的情況(如果有這種情況)。
該代碼適用於MySql,但可以在任何rdbms中找到所有使用的功能。
參見演示 。
結果:
| type | counter |
| ---- | ------- |
| a | 1 |
| b | 2 |
| c | 1 |
邏輯可能是提取字符串的一部分直到破折號(如果存在),然后按type
列分組。 但是方法因DBMS
異。
如果您使用的是Oracle
,請考慮:
select type,
count( distinct
case when instr(contract_id,'-') > 0 then
substr(contract_id,1,instr(contract_id,'-')-1)
else
contract_id
end) as countocc
from db_address d
group by type
如果是SQL Server
,請考慮:
select type,
count( distinct
case when charindex('-',contract_id) > 0 then
left(contract_id,charindex('-',contract_id)-1)
else
contract_id
end) as countocc
from db_address d
group by type;
如果是MySQL
,請考慮:
select type,
count(distinct substring(contract_id,1,instr(contract_id,'-')-1)) as countocc
from db_address d
group by type;
如果是PostGRES
,請考慮:
select type,
count( distinct
case when strpos(contract_id,'-') > 0 then
substr(contract_id,1,strpos(contract_id,'-')-1)
else
contract_id
end) as countocc
from db_address d
group by type;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.