使用 SSMS 18.11.1
我有一個名為 email_archive 的表,每一行都有一個名為附件的列。每行也有列companyID
我正在嘗試獲取附件列中沒有任何內容的每個 customerID 條目的百分比。
有什么建議?
按要求提供表格示例資料
|id |CompanyID| Originator | MSGText |Attachment |sendstatus|
| - | ------- | ----------- | --------------| --------- | -------- |
|1 | HG1 |test@test.com|This is a test1| roses.txt |Delivered |
|2 | HG3 |test@test.com|This is a test1| roses.txt |Failed |
|3 | HG4 |test@test.com|This is a test1| roses.txt |Failed |
|4 | HG5 |test@test.com|This is a test1| null |Delivered |
|5 | HG1 |test@test.com|This is a test1| roses.txt |Failed |
|6 | HG1 |test@test.com|This is a test1| roses.txt |Delivered |
|7 | HG3 |test@test.com|This is a test1| null |Failed |
|8 | HG4 |test@test.com|This is a test1| roses.txt |Failed |
|9 | HG5 |test@test.com|This is a test1| null |Delivered |
|10 | HG1 |test@test.com|This is a test1| roses.txt |Failed |
抱歉,上面在預覽中顯示為表格,但不會讓我發布,因為它認為它的代碼需要縮進
尋找結果,例如
HG1 0%
HG2 0%
HG3 50%
HG4 0%
HG5 100%
非常感謝您提前提供的任何幫助。
uj5u.com熱心網友回復:
簡單地說,您想將不帶附件的行數除以總行數。
我在這里假設沒有附件的行有一個空字串而不是 NULL。以下兩個查詢應該為您提供所需的數字。
SELECT COUNT(CompanyID) FROM email_archive WHERE attachment = ''
SELECT COUNT(CompanyID) FROM email_archive
如果您想在 SQL 中進行計算,您需要先將它們轉換為十進制,因為如果您將從 COUNT 獲得的兩個 INT 相除,您最終會得到一個 INT 而不是小數。
select convert(
decimal(18, 0),
(
SELECT COUNT(CompanyID)
FROM email_archive
WHERE attachment = ''
)
) / convert(
decimal(18, 0),
(
SELECT COUNT(CompanyID)
FROM email_archive
)
)
uj5u.com熱心網友回復:
我通過 CompanyID 加入了兩個表,以獲取那些為 null 的附件和那些不為 null 的附件的計數。然后我計算了百分比,結果我連接了 '%' 字串。
select ea1.CompanyID,
case when max(ea3.cnt) is not null then
CONCAT(round((max(cast(ea3.cnt as float))/count(*) *100), 2), '%')
else
'0%'
end prc
from email_archive ea1
left join (select count(*) cnt
, ea2.CompanyID
from email_archive ea2
where ea2.attachment is null
group by ea2.CompanyID ) ea3
on ea1.CompanyID = ea3.CompanyID
group by ea1.CompanyID
這是一個演示
uj5u.com熱心網友回復:
您可以只使用條件聚合。
為了避免
int/decimal問題,乘以100.0
SELECT
t.CompanyID,
Pct = COUNT(CASE WHEN t.attachment IS NULL THEN 1 END) * 100.0 / COUNT(*)
FROM YourTable t
GROUP BY
t.CompanyID;
db<>小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/447905.html
