sql - 如何从一列中获取不同的数据

标签 sql sql-server

我需要获取订阅已失效的所有成员(member)的成员(member)个人数据,即订阅结束日期在 2020 年 3 月 31 日之前,但我只想显示一条成员(member)记录(按成员(member)号区分),最好是最新的一个

我尝试过 ROW_NUMBER() 解决方案 SQL - Distinct One Col, Select Multiple other?和交叉应用解决方案 sql distinct, getting 2 columns但我无法让它工作。

SELECT membershipnumber AS Id, 
       subscription.enddate 
FROM   [dbo].[userprofile] 
       INNER JOIN dbo.subscription 
               ON userprofile.id = subscription.userprofileid 
       INNER JOIN dbo.subscriptiontype 
               ON subscriptiontype.id = subscription.subscriptiontypeid 

输出为

Id  Enddate
1   2006-04-01 00:00:00.000
1   2001-04-01 00:00:00.000
1   1999-04-01 00:00:00.000
1   1998-04-01 00:00:00.000
1   2008-04-01 00:00:00.000
1   2007-04-01 00:00:00.000
1   2011-04-01 00:00:00.000
1   2005-04-01 00:00:00.000
1   2000-04-01 00:00:00.000
1   1997-04-01 00:00:00.000
2   1999-04-01 00:00:00.000
2   2012-04-01 00:00:00.000
2   2004-04-01 00:00:00.000
2   2001-04-01 00:00:00.000
2   2018-04-01 00:00:00.000
2   2009-04-01 00:00:00.000
2   2005-04-01 00:00:00.000
2   1997-04-01 00:00:00.000

期望的输出

ID 结束日期

1   2011-04-01 00:00:00.000
2   2018-04-01 00:00:00.000

最佳答案

已解决的sql答案

;WITH cte 
     AS (SELECT membershipnumber                        AS Id, 
                subscription.enddate, 
                Row_number() 
                  OVER ( 
                    partition BY membershipnumber 
                    ORDER BY subscription.enddate DESC) AS rownumber 
         FROM   [dbo].[userprofile] 
                INNER JOIN dbo.subscription 
                        ON userprofile.id = subscription.userprofileid 
                INNER JOIN dbo.subscriptiontype 
                        ON subscriptiontype.id = subscription.subscriptiontypeid 
        ) 
SELECT * 
FROM   cte 
WHERE  rownumber = 1 

https://stackoverflow.com/a/6841644/5859743

关于sql - 如何从一列中获取不同的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57391394/

相关文章:

php - 如何在另一个sql查询的一段时间内运行一个sql查询?

sql-server - TSQL在存储过程中动态添加列

SQL Datediff - 查找行之间的 datediff

sql - 如果一个表中为空,则从其他中选择

MySQL 查询不正确

sql - 在 SQL Server 中从 XML 中提取值

sql-server - 计算多列行的哈希值或校验和的最有效方法?

sql-server - 仅授予对数据库的 CREATE TABLE 权限,但不授予 ALTER

sql - 将数据集插入数据库表时出错

php - 更新 MySQL 表中最后 20 行的特定列?