我想查询一个表,其中我需要包含两列唯一值的结果。对于例如
表
EnquiryId | EquipmentId | Price
-----------+--------------+-------
1 | E20 | 10
1 | E50 | 40
1 | E60 | 20
2 | E30 | 90
2 | E20 | 10
2 | E90 | 10
3 | E90 | 10
3 | E60 | 10
每个EnquiryId, EquipmentId
在表格中都是唯一的。现在我想要一个结果,我可以得到这样的东西
EnquiryId | EquipmentId | Price
-----------+--------------+-------
1 | E20 | 10
2 | E30 | 90
3 | E90 | 10
在结果中,表中存在的每个enquiryId
都应该唯一显示。
如果假设我有3 EquipmentIds
" E20,E50,E60"对于EnquiryId
" 1" ..只应从这三个值中显示任意随机EquipmentId
。
任何帮助将不胜感激。提前谢谢。
答案 0 :(得分:2)
;WITH cte AS
(
SELECT *,
ROW_NUMBER() OVER
(PARTITION BY enquiryID
ORDER BY enquiryID ) AS RN
FROM tbl
)
SELECT enquiryID,equipmentID,Price
FROM cte
WHERE RN=1
答案 1 :(得分:1)
以下代码必须帮助您.. 对不起,我最终只是在一个冗长的解决方案。在SSMS中运行它并查看结果。
Declare @tab table (EnquiryId int, EquipmentId varchar(10),Price int)
Insert into @tab values
(1,'E20',10),
(1,'E50',40),
(1,'E60',20),
(2,'E30',90),
(2,'E20',10),
(2,'E90',10),
(3,'E90',10),
(3,'E60',10)
----------------------------------------------
Declare @s int = 1
Declare @e int,@z varchar(10)
Declare @Equipment table (EquipmentId varchar(10),ind int)
Insert into @Equipment (EquipmentId) Select Distinct EquipmentId From @tab
Declare @Enquiry table (id int identity(1,1),EnquiryId int,EquipmentId varchar(10))
Insert into @Enquiry (EnquiryId) Select Distinct EnquiryId From @tab
Set @e = @@ROWCOUNT
While @s <= @e
begin
Select Top 1 @z = T.EquipmentId
From @tab T
Join @Enquiry E On T.EnquiryId = E.EnquiryId
Join @Equipment Eq On Eq.EquipmentId = T.EquipmentId
Where E.id = @s
And Eq.ind is Null
Order by NEWID()
update @Enquiry
Set EquipmentId = @z
Where id = @s
update @Equipment
Set ind = 1
Where EquipmentId = @z
Set @s = @s + 1
End
Select T.EnquiryId,T.EquipmentId,T.Price
From @tab T
left join @Enquiry E on T.EnquiryId = E.EnquiryId
Where T.EquipmentId = E.EquipmentId
答案 2 :(得分:0)
您可以使用GROUP BY(典型方式)删除重复值。
基本步骤是: