简体   繁体   English

SQL Server 2005中的不同查询

[英]Distinct query in sql server 2005

I have a table which have three fields ID,Name,aDate. 我有一个表,其中包含三个字段ID,Name,aDate。 I want result on distinct name and i want date to be in result. 我希望结果使用不同的名称,并且希望日期生效。 I am using query as 我正在使用查询

Select distinct(Name),adate from table_name.

But i am getting wrong results.i think sql is appling distinct on combination of both fields. 但是我得到了错误的结果。我认为sql在这两个字段的组合上应用不同。 What i do help me. 我所做的是帮助我的。 I want distinct name values with their respective adate field. 我想要具有各自日期字段的不同名称值。

If you only want ONE Date per Name then you have to specify which date: 如果每个名称仅需要一个日期,则必须指定哪个日期:

Eg: 例如:

 SELECT Name, Max(aDate)
 FROM table_name
 GROUP BY Name

Since this statement uses GROUP BY Name it will only return one row for each Name. 由于此语句使用GROUP BY Name因此每个Name仅返回一行。 Since it uses an aggregation of aDate (in my example the MAX() function) it will return the appropriate date which you want. 由于它使用aDate的聚合(在我的示例中是MAX()函数),因此它将返回您想要的适当日期。

In general you should try to avoid the use of the DISTINCT keyword. 通常,您应该尝试避免使用DISTINCT关键字。 It is seldom the right approach. 这很少是正确的方法。

If you simply want the list of distinct names used in your table you can use 如果您只想在表中使用不同名称的列表,则可以使用

 SELECT DISTINCT Name
 FROM table_name

which will return the same results as 这将返回相同的结果。

 SELECT Name
 FROM table_name
 GROUP BY Name

Distinct does not work on one field it works across the whole row of fields in query. Distinct不适用于一个字段,它适用于查询的整个字段行。 So what you are asking does not make sense. 因此,您要问的没有任何意义。

If your table has rows like this 如果您的表中有这样的行

|ID|Name|Date|
|1|John|2011-4-1|
|2|John|2011-4-2|
|3|John|2011-4-2|

then when you call Select distinct name, date what are you expecting to see in the date column? 那么当您致电“ Select distinct name, date请注明您希望在日期栏中看到的内容?

you need to decide which date. 您需要决定哪个日期。

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

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