假设我有下表:
id | name | type
1 | test1 | value1
2 | test2 | value1
3 | test3 | value1
4 | test4 | value2
5 | test5 | value2
6 | test6 | value3
我该如何编写查询以返回记录,但首先需要使用
答案 0 :(得分:2)
如果您可以使用窗口功能,请使用ROW_NUMBER() OVER (PARTITION BY type)
。它将为每种类型分配行号:
TableName.find_by_sql(
select *, row_number() over (partition by type order by (select null)) rn
from table_name
order by rn, type
)
输出:
| id | name | type | rn |
|----|-------|--------|----|
| 1 | test1 | value1 | 1 |
| 4 | test4 | value2 | 1 |
| 6 | test6 | value3 | 1 |
| 2 | test2 | value1 | 2 |
| 5 | test5 | value2 | 2 |
| 3 | test3 | value1 | 3 |
答案 1 :(得分:0)
如果我正确理解,则需要进行如下查询。
SELECT t.name,
t1.type
FROM (SELECT DISTINCT name
FROM yourtable) t
CROSS JOIN (SELECT DISTINCT type
FROM yourtable)t1