我已經使用此查詢兩天并閱讀了很多帖子,但仍然無法弄清楚如何處理這種情況。
我的桌子是這樣的:
------ ------
| Type | ID |
------ ------
| A | 1339 |
| A | 1156 |
| B | 1156 |
| A | 1192 |
| B | 1214 |
| B | 1202 |
| C | 1202 |
| A | 1207 |
| B | 1207 |
| C | 1207 |
| B | 1241 |
------ ------
我需要計算 B 有多少個 ID,但該 ID 在 A 中沒有重復。
具體而言,應反映兩個標準:
標準 1:B 僅在 B 中有多少個 ID?
標準 2:B 在 A 和 B 中有多少個 ID?
在這種情況下,C 無關緊要。
我的預期結果應該是這樣的:
--------------- -----------
| Ds in A and B | IDs in B |
---------------------------
| 2 | 4 |
--------------- -----------
uj5u.com熱心網友回復:
似乎它可以是這樣的:
select Count(Id) -- Or if we want distinct Ids: Count(Distinct Id)
from MyTable
where Type = 'A' -- Id has Type 'A'
and Id not in (select b.Id -- Not appears among of type 'B'
from MyTable b
where b.Type = 'B')
在這里,我們得到了所有Id
有型別A
但沒有的B
;查找僅Id
具有A
型別的 s:
select Count(Id) -- Or if we want distinct Ids: Count(Distinct Id)
from MyTable
where Type = 'A'
and Id not in (select b.Id
from MyTable b
where b.Type <> 'A')
要獲得Id
既具有型別A
又B
只是更改not in
為in
(或進行自我加入)的 s:
select Count(Id) -- Or if we want distinct Ids: Count(Distinct Id)
from MyTable
where Type = 'A'
and Id in (select b.Id
from MyTable b
where b.Type = 'B')
uj5u.com熱心網友回復:
嘗試使用 COUNT 和 DISTINCT。但不要忘記選擇 B 型別行的 WHERE 條件。這是您最終得到的查詢型別:
SELECT COUNT(DISTINCT ID) FROM table WHERE Type = "B"
uj5u.com熱心網友回復:
B中的ID如何等于4?B中有五個ID,(B而不是A)中有tree id
select COUNT(DISTINCT ID) as AandB from tTable where Type='B' and ID
in(select id from tTable where Type='A')
select COUNT(DISTINCT ID) as B from tTable where Type='B'
select COUNT(DISTINCT ID) as Bnot_inA from tTable where Type='B' and ID not
in(select id from tTable where Type='A')
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/510535.html
標籤:sql
上一篇:SQL中的GROUPBY子句