[英]Select distinct set of values values from table in MS Sql
I have table in my db which is in MSSQL having following structure 我的数据库中的表在MSSQL中具有以下结构
DayID Sequence Cities Title Hotels
----------------------------------------------------------------
1 1 Manali Day1 Hotel A
2 2 Manali Day2 Hotel B
3 2 Delhi Day3 Hotel C
4 3 Delhi Day4 Hotel D
5 3 Manali Day5 Hotel E
6 4 Manali Day6 Hotel F
Now I need The result as following 现在我需要结果如下
Cities
------
Manali
Delhi
Manali.
I have used group by Cities but it is giving only two cities 我使用了按城市分组,但它只给了两个城市
Manali
Delhi
But I need following output. 但是我需要以下输出。
Manali
Delhi
Manali
Please Suggest. 请提出建议。
Thanks in Advance. 提前致谢。
Try this: 尝试这个:
SELECT Cities
FROM (
SELECT Cities, DayID,
ROW_NUMBER() OVER (ORDER BY DayID) -
ROW_NUMBER() OVER (PARTITION BY Cities ORDER BY DayID) AS grp
FROM mytable) AS t
GROUP BY Cities, grp
ORDER BY MIN(DayID)
Calculated field grp
identifies islands of consecutive records having the same Cities
value. 计算字段
grp
标识具有相同“ Cities
值的连续记录的孤岛。 Using this field in a GROUP BY
clause, we can extract the required sequence of Cities
values. 在
GROUP BY
子句中使用此字段,我们可以提取所需的Cities
值序列。
Note: The above query works in SQL Server. 注意:上面的查询在SQL Server中有效。
根据要求,您可以按以下方式分组:从表中按城市选择城市
First make sure the table is sorted so we can use the 'by' option in the data step: 首先,确保表格已排序,以便我们可以在数据步骤中使用“ by”选项:
proc sort data=tablename;
by sequence cities;
run;
In the data step use the 'by' clause to select the first row of each group and output. 在数据步骤中,使用“ by”子句选择每个组的第一行并输出。 Only 'keep' cities as requested by user
仅根据用户要求“保留”城市
data desired;
keep cities;
set tablename;
by sequence cities;
if first.cities then output;
run;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.