如何过滤sql副本?

时间:2012-07-24 07:46:24

标签: tsql sql-server-2008-r2

我的问题:我希望记录不重复,在同一个表和多个表中?如何在SQL中继续执行此操作?

让我解释一下我的尝试:

Select distinct Col1, col2
from Table
where order id = 143

输出

VolumeAnswer1    AreaAnswer1    heightAnswer1
VolumeAnswer2    AreaAnswer1    heightAnswer2
VolumeAnswer3    AreaAnswer1    heightAnswer2

预期输出
它显示了第二个表的副本,但我需要输出如:

VolumeAnswer1    AreaAnswer1    heightAnswer1
VolumeAnswer2                   heightAnswer2
VolumeAnswer3

对于多个表我需要相同的场景,我也为连接找到了相同的副本。如果无法在SQL Server中处理,我们如何在.Net中处理它?我使用了多个选择但他们曾经在单选中更改它。每个列都应该在下拉列表中绑定...

1 个答案:

答案 0 :(得分:1)

这样的事情可能是一个很好的起点:

;with cte1 as (
Select col1, cnt1
From (
  Select
    col1
    ,row_number() over(Partition by col1 Order by col1) as cnt1
  From tbltest) as tbl_sub1
Where cnt1 = 1
), cte2 as (
Select col2, cnt2
From (
  Select
    col2
    ,row_number() over(Partition by col2 Order by col2) as cnt2
  From tbltest) as tbl_sub2
Where cnt2 = 1
), cte3 as (
Select col3, cnt3
From (
  Select
    col3
    ,row_number() over(Partition by col3 Order by col3) as cnt3
  From tbltest) as tbl_sub3
Where cnt3 = 1
)
Select
col1, col2, col3
From cte1
full join cte2 on col1 = col2
full join cte3 on col1 = col3

Sql Fiddle显示示例:http://sqlfiddle.com/#!3/c9127/1