简体   繁体   English

DISTINCT仅适用于一列,而另一列是随机的吗?

[英]DISTINCT for only one Column and other column random?

I have one Table name Demodata which have two column col1 and col2. 我有一个表名称Demodata,其中有两列col1和col2。 data of table is 表的数据为

col1   col2    
1        5  
1        6    
2        7    
3        8    
3        9    
4        10

and after SELECT command we need this data SELECT命令之后,我们需要此数据

col1    Col2    
1        5    
         6    
2        7   
3        8   
         9   
4        10

is this possible then what is query please guide me 这可能吗,查询是什么,请指导我

Try this 尝试这个

    SELECT CASE WHEN RN > 1 THEN NULL ELSE Col1 END,Col2
    FROM
    (
    SELECT *,Row_Number() Over(Partition by col1 order by col1) AS RN
    From yourTable
    ) AS T

No it is not possible. 不,这是不可能的。

SQL Server result sets are row based not tree based. SQL Server结果集基于行而不是基于树。 You must have a value for each column (alternatively a NULL value). 您必须为每个列都有一个值(或者为NULL值)。

What you can do is grouping by col1 and run an aggregate function on the values of col2 (possibly the STUFF function). 您可以按col1进行分组,然后对col2的值运行一个聚合函数(可能是STUFF函数)。

You can do this in SQL, using row_number() : 可以使用row_number()在SQL中执行此操作:

select (case when row_number() over (partition by col1 order by col2) = 1
             then col1
        end), col2
from table t
order by col1, col2;

Notice that the ordering is important. 请注意,排序很重要。 The way you have written the result set, the data is ordered by col1 and then col2 . 写入结果集的方式是,数据按col1然后col2排序。 Result sets do not have an inherent ordering, unless you include an order by clause. 结果集没有固有的顺序,除非您包括order by子句。

Also, I have used NULL for the missing values. 另外,我对缺失值使用了NULL

And, finally, although this can be done in SQL, it is often preferable to do these types of manipulations on the client side. 最后,尽管这可以在SQL中完成,但通常最好在客户端进行这些类型的操作。

What do you want to select on the duplicates, an empty string, NULL , 0, ... ? 您想在重复项中选择什么,一个空字符串NULL ,0,...?

I presume NULL , you can use a CTE with ROW_NUMBER and CASE on col1 : 我假设为NULL ,则可以在col1上将CTE与ROW_NUMBERCASE使用:

WITH CTE AS(
  SELECT RN = ROW_NUMBER() OVER (PARTITION BY col1 
                               ORDER BY (SELECT 1))
        , col1, col2
  FROM Demodata 
)
SELECT col1 = CASE WHEN RN = 1 THEN col1 ELSE NULL END, col2
FROM CTE

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM