按不同的值选择所有行,并限制不同的值

时间:2019-01-24 10:48:06

标签: sql postgresql

假设我们有2张桌子:

Table1:         Table2:
id | t2id       id | col
----------      ----------
1  |  1         1  |  a
2  |  2         2  |  b
3  |  2         3  |  c
4  |  1         4  |  d
5  |  3         5  |  e
6  |  3         6  |  f
7  |  4         7  |  g
8  |  5         8  |  h
9  |  1         9  |  i
10 |  4         10 |  j

我的问题是: 是否有简短方式Table1.t2id列的不同结果设置限制?
例如:如果limit = 2,则选择t2id从1到2(或任何其他值)的所有行。

预期结果(带有limit = 2):

Res:
id | t2id
----------
1  |  1
2  |  2
3  |  2
4  |  1
9  |  1


注意:

接受任何信息或建议

3 个答案:

答案 0 :(得分:0)

您可以仅使用where子句

["08:00 AM","08:15 AM","08:30 AM","08:45 AM",
 "09:00 AM","09:15 AM","09:30 AM","09:45 AM",
 "10:00 AM","10:15 AM","10:30 AM","10:45 AM",
 "11:00 AM","11:15 AM","11:30 AM","11:45 AM",
 "04:00 PM","04:15 PM","04:30 PM","04:45 PM",
 "05:00 PM","05:15 PM","05:30 PM","05:45 PM",
"06:00 PM","06:15 PM","06:30 PM","06:45 PM"]

或者您可以在..之间使用..

Select id,t2id
from table1
where t2id<=2

答案 1 :(得分:0)

我相信您想要

  1. 使用所需的所有列以及该列创建一个子查询:DENSE_RANK() OVER (ORDER BY Table1.t2id) AS MyRank

  2. 在子查询之外,在where上添加MyRank

完整的解决方案:

SELECT id, tb2id
FROM (
SELECT id, tb2id, DENSE_RANK() OVER (ORDER BY Table1.t2id) AS MyRank
FROM table1
) MySubQuery
WHERE MyRank <= 2

这将适用于具有table2(潜在多重性增加)和tb2id中的非连续值的JOIN s。

答案 2 :(得分:0)

您也可以使用in

select t1.*
from table1 t1
where t1.t2_id in (select t2.id from table2 t2 limit 2);

这种方法的优点是很容易将其随机化:

select t1.*
from table1 t1
where t1.t2_id in (select t2.id from table2 t2 order by random() limit 2);