如何使用部分不同的SELECT语句?
Col1 Col2 Col3 Col4
data1 data2 data3 abc
data2 data3 data2 abcde
对于上面的数据集,仅返回那些具有不同(Col1,Col2,Col3)的数据集:
INSERT INTO #tmp
(
[Col1],
[Col2],
[Col3],
[Col4]
)
SELECT DISTINCT Col1, Col2, Col3, Col4
FROM store s
INNER JOIN address a ON s.addressid = a.id
最终我想将其插入到如下所示的临时表中。
class Field < ApplicationRecord
belongs_to :semester
accepts_nested_attributes_for :semester, allow_destroy: true
end
答案 0 :(得分:3)
由于您不在乎所需的col4值中的哪一个,因此可以获取最小的col4值,然后执行
SELECT Col1, Col2, Col3, min(Col4)
FROM store s
INNER JOIN address a ON s.addressid = a.id
GROUP BY Col1, Col2, Col3
答案 1 :(得分:1)
您还可以将CTE与排名功能配合使用。
; with subQry as (
select col1, col2, col3, col4, rownumber() over(partition by col1, col2, col3 order by col1, col2, col3) rnk
FROM store s
INNER JOIN address a ON s.addressid = a.id
)
select * from subQry where rnk = 1;