如何在我的SQL Server中选择?
示例:
ID Name Event
------------------------------
1 Mary Running 20/10/2017
1 Mary Running 20/10/2017
1 Mary Stopped 20/10/2017
1 Mary Running 20/10/2017
2 John Stopped 20/10/2017
2 John Running 20/10/2017
3 Lucy Stopped 20/10/2017
3 Lucy Running 20/10/2017
3 Lucy Stopped 20/10/2017
我想为每个ID显示结果1,但只能在一行中显示
ID Name Event Row
-----------------------------------
1 Mary Running 20/10/2017 1
1 Mary Running 20/10/2017 0
1 Mary Stopped 20/10/2017 0
1 Mary Running 20/10/2017 0
2 John Stopped 20/10/2017 1
2 John Running 20/10/2017 0
3 Lucy Stopped 20/10/2017 1
3 Lucy Running 20/10/2017 0
3 Lucy Stopped 20/10/2017 0
答案 0 :(得分:4)
我们无法在没有您查询的情况下给出具体答案,因此这里是一般性答案。使用ROW_NUMBER()
为每行提供一个数字,然后使用CASE
语句将除第1行之外的所有行替换为0:
SELECT ID, Name, Event,
CASE WHEN RN = 1 THEN 1 ELSE 0 END [Row]
FROM (SELECT ID, Name, Event,
ROW_NUMBER() over (PARTITION BY ID ORDER BY ID) RN --Add Event to the
--partition if needed
FROM YourTable
) A
正如@JNevill所提到的,您可以通过将窗口函数直接添加到CASE
语句来清除它以避免子查询:
SELECT ID, Name, Event,
CASE WHEN ROW_NUMBER() over (PARTITION BY ID ORDER BY ID) = 1
THEN 1
ELSE 0
END [Row]
FROM YourTable
答案 1 :(得分:0)
要区别于ID和日期,您可以使用以下代码:
SELECT ID,RIGHT([Event],10) FROM Some_table GROUP BY ID,RIGHT([Event],10)
OR
SELECT distinct ID,RIGHT([Event],10) FROM Event_table
如果添加一行,例如:
(1,'玛丽','运行21/10 / 2017')
你会得到两行ID 1,一个会给20/10/2017,另一行会给21/10/2017。
对1' s和0'的列是否有特殊需要?