繁体   English   中英

SELECT DISTINCT值-多个具有相同ID的行-多个条件

[英]SELECT DISTINCT values - multiple rows of same ID - multiple conditions

这是我的出发桌:

User_ID | FIELD_KEY    | VALUE
11      |  name        |  John
11      |  test1_score |  9
11      |  test2_score |  6
11      |  test3_score |  8
11      |  test5_score |  3
27      |  name        |  Peter
27      |  test1_score |  7
27      |  test3_score |  3
28      |  name        |  Nick
28      |  test1_score |  6
28      |  test2_score |  5
33      |  name        |  Felix
33      |  test1_score |  7
33      |  test2_score |  3

如何选择以下项的唯一User_ID

条件:

  • 同时具有两个条目的所有用户:test1_score和test2_score
  • test1_score> = 7的所有用户
  • 按test1_score ASC排序

似乎是一个挑战...

一个查询甚至可能吗?

在此示例中,结果应该是两个具有User_ID的用户:#11和#33。 这是因为即使用户#28同时具有test1_score和test2_score条目,也仅对于用户#11和#33 test1_score> = 7。

理想情况下,我会得到如下结果:

User_ID   |   NAME         | TEST1_SCORE  |  TEST2_SCORE    |
33        |     Felix      |    7         |  3              |
11        |     John       |    9         |  6              |

很感谢任何形式的帮助。

谢谢!

这就是我要做的

select distinct t.id, name, test1_score, test2_score from t
inner join (select id, value test1_score from t where field_key = 'test1_score' and value >= 7) t1 on (t1.id = t.id)
inner join (select id, value test2_score from t where field_key = 'test2_score' and value is not null) t2 on (t2.id = t.id)
inner join (select id, value name from t where field_key = 'name') t3 on (t3.id = t.id)
order by test1_score;

sqlfiddle

这对您有用吗?

SELECT A.USER_ID, 
       A.VALUE AS "NAME", 
       B.VALUE AS "TEST1_SCORE", 
       C.VALUE AS "TEST2_SCORE"
FROM MYTABLE A, MYTABLE B, MYTABLE C
WHERE A.USER_ID = B.USER_ID
  AND A.USER_ID = C.USER_ID
  AND A.FIELD_KEY = 'name'
  AND B.FIELD_KEY = 'test1_score'
  AND B.VALUE >= 7
  AND C.FIELD_KEY = 'test2_score'
ORDER BY 3 ASC
;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM