簡體   English   中英

如何在 MySQL 中獲得條件滿足的行的 position

[英]How to get position of rows where a condition meet in MySQL

這是我的樣本數據集...

CREATE TABLE blockhashtable (
    id SERIAL PRIMARY KEY 
    ,pos int
    ,filehash varchar(35)
    ,blockhash varchar(130) 
);    

insert into blockhashtable 
(pos,filehash,blockhash) values 
(1, "randommd51", "randstr1"),
(2, "randommd51", "randstr2"),
(3, "randommd51", "randstr3"),
(1, "randommd52", "randstr2"),
(2, "randommd52", "randstr2"),
(3, "randommd52", "randstr1"),
(4, "randommd52", "randstr7"),
(1, "randommd53", "randstr2"),
(2, "randommd53", "randstr1"),
(3, "randommd53", "randstr2"),
(4, "randommd53", "randstr3"),
(1, "randommd54", "randstr4"),
(2, "randommd54", "randstr55");

...和相同的http://sqlfiddle.com/#!9/e5b201/14的小提琴

這是我當前的 SQL 查詢和 output:

select pos,filehash,avg( (blockhash in ('randstr1', 'randstr2', 'randstr3') )) as matching_ratio from blockhashtable group by filehash;

pos filehash    matching_ratio
1   randommd51  1
1   randommd52  0.75
1   randommd53  1
1   randommd54  0

我預期的 output 是這樣的:

pos       filehash      matching_ratio
1,2       randommd51    1
1,3       randommd52    0.5
1,2,4     randommd53    0.75
0         randommd54    0

最后rowpos也可以是1 ,我可以稍后使用 python 中的自定義條件將其刪除。

基本上,在我的 python 列表中, randstr2只重復一次,所以我只希望在 SQL 查詢中找到最多一個匹配項。 這就是為什么matching_ratio在我預期的output中不同的原因。

我看不出你的結果集與你的數據集是如何對應的,但你似乎在追求這樣的東西......

SELECT filehash
     , GROUP_CONCAT(pos ORDER BY pos) pos
     , 1-(COUNT(DISTINCT blockhash IN('randstr1','randstr2','randstr3'))/(COUNT(*))) ratio
  FROM blockhashtable
 GROUP
    BY filehash;
+------------+---------+--------+
| filehash   | pos     | ratio  |
+------------+---------+--------+
| randommd51 | 1,2,3   | 0.6667 |
| randommd52 | 1,2,3,4 | 0.5000 |
| randommd53 | 1,2,3,4 | 0.7500 |
| randommd54 | 1,2     | 0.5000 |
+------------+---------+--------+

暫無
暫無

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

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