Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择“与视图不同”_Sql_Sql Server_Select_Sqlcommand - Fatal编程技术网

Sql 选择“与视图不同”

Sql 选择“与视图不同”,sql,sql-server,select,sqlcommand,Sql,Sql Server,Select,Sqlcommand,假设我有一个包含以下数据的视图 Name Image ---- ---------- A Image1 A Image2 A Image3 B Image4 B Image5 现在,我想要的是为每个名称只选择一行,不管我希望结果是什么,例如: Name Image ---- ---------- A Image1 B Image4 另一

假设我有一个包含以下数据的视图

Name      Image
----    ----------
 A         Image1
 A         Image2
 A         Image3
 B         Image4
 B         Image5
现在,我想要的是为每个名称只选择一行,不管我希望结果是什么,例如:

Name      Image
----    ----------
 A         Image1
 B         Image4
另一个可能更接近我需要的场景是,如果我们选择一个销售产品的站点,每个产品都有多个图像,那么如何只选择一个图像作为封面显示(假设第一个)。我使用了Distinct,但它不起作用,因为每行有不同的图像

谢谢


Rasha

对于您问题中的数据,简单的汇总即可:

select name, min(image)
from t
group by name
如果您有多个列,并且希望所有行都来自同一个表:

select t.*
from (select t.*,
             row_number() over (partition by name order by newid()) as seqnum
      from t
     ) t
where seqnum = 1;

row\u number()
函数为具有相同名称的所有行分配一个序列号。newid()的
order()进行了随机排序。

非常感谢……这正是我需要的:)