簡體   English   中英

sql 統計每行屬性值的出現次數,區分大小寫

[英]Count occurence of attribute values in each row with case-sensitive in sql

我有表( notes_subject )結構 -

+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| id           | int         | NO   | PRI | NULL    | auto_increment |
| user_id      | int         | NO   |     | NULL    |                |
| note_id      | varchar(25) | NO   | MUL | NULL    |                |
| subject_name | text        | NO   |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+

和存儲在此表中的數據 -

+----+---------+--------------+--------------+
| id | user_id | note_id      | subject_name |
+----+---------+--------------+--------------+
| 10 |       2 | UdMs870BSswp | CN           |
| 12 |       2 | 8stMvslwIGr2 | CN           |
| 13 |       2 | PB3KNbbFkaUm | cn           |
+----+---------+--------------+--------------+

注:CN 和 cn(小寫)不同。

我想通過此表中的user_id計算每個subject_name的出現次數。 所以我運行查詢 -

SELECT subject_name, COUNT(subject_name) 
FROM notes_subject where user_id=2 GROUP BY subject_name;

它取得了-

+--------------+---------------------+
| subject_name | COUNT(subject_name) |
+--------------+---------------------+
| CN           |                   3 |
+--------------+---------------------+

但這不是正確的結果,因為 CN 和 cn 不同。
我還想要結果中的 id、user_id、note_id。

如果你的數據庫支持window functions ,我想你想要這樣的東西。 嘗試使用collate utf8mb4_bin看看這是否有助於您需要的區分大小寫

select id, 
       user_id, 
       note_id, 
       subject_name, 
       count(subject_name collate utf8mb4_bin) over (partition by user_id, subject_name collate utf8mb4_bin) 
from notes_subject; 

如果window functions了,也可以單獨聚合,再join回主表。

演示

發布另一種選擇,即selecting the group by column as a binary field

使用 MYSQL 8.0 版本在dbfiddle中測試

SELECT cast(subject_name as binary) subject_name, COUNT(subject_name)  cnt
  FROM notes_subject 
 WHERE user_id=2 
GROUP BY cast(subject_name as binary)

您可以簡單地使用 Binary 來轉換它。

SELECT count(*), CAST(subject_name as BINARY) AS lastname_cs 
FROM notes_subject where user_id=2 
GROUP BY CAST(subject_name as BINARY); 

暫無
暫無

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

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