sql-server - 显示来自 Join 查询的不同数据

标签 sql-server join distinct case

基本上我有 2 个表。让我们说 A 和 B。

A 有像 id(PK), pin, name, address 这样的列

id(PK)  pin             name    address
1        aaa-111-aaa    AAA ------
2        bbb-222-bbb    BBB ------
3        ccc-333-ccc    CCC --------

B 有 appName、apprequestTime、appAccectTime、id(FK) 等列。

appName apprequestTime  appAccectTime    id(FK).
LLL          2012-4-01  2012-4-01    1
NNN          2012-4-08  2012-5-01    2
QQQ          2012-4-05  2012-4-01    1
MMM          2012-4-02  2012-4-02    2
PPP          2012-5-01  2012-5-01    1

B 表中可以有多个id 行,因为它是外键。

现在,问题是我正在尝试获取某个 apprequestTime 的一个 pin 的所有记录。

我正在尝试内部连接,但由于表 B 中的 ID,它显示了 pin。

pin         apprequestTime
aaa-111-aaa     2012-4-01
aaa-111-aaa     2012-4-05
bbb-222-bbb     2012-4-08
bbb-222-bbb     2012-4-02

但我期望的结果应该是:

pin            apprequestTime
aaa-111-aaa    2012-4-01
               2012-4-05
bbb-222-bbb    2012-4-08
               2012-4-02

谁能帮忙:)

最佳答案

在 SQL Server 2005+ 中,您可以对此类请求使用 row_number():

;with cte as
(
  select a.pin, b.apprequestTime,
    row_number() over(partition by a.pin 
                      order by b.apprequestTime) rn
  from tablea a
  inner join tableb b
    on a.id = b.id
) 
select case when rn = 1 then pin else '' end pin, 
  apprequestTime
from cte;

参见 SQL Fiddle with Demo

或者没有 CTE:

select case when rn = 1 then pin else '' end pin, 
  apprequestTime
from 
(
  select a.pin, b.apprequestTime,
    row_number() over(partition by a.pin 
                      order by b.apprequestTime) rn
  from tablea a
  inner join tableb b
    on a.id = b.id
) t1

参见 SQL Fiddle with Demo

关于sql-server - 显示来自 Join 查询的不同数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13050536/

相关文章:

mysql - 存储用户并传入单个表或单独的表

c# - 如何使用单个查询将数据集中的多条记录插入到 SQL Server 2005 中?

mysql - SQL:在不覆盖行的情况下加入后的 GROUP BY?

MySQL,计算跨月的不同元素

sql - Oracle sql 不同查询

SQL查询: Using DISTINCT/UNIQUE and SUM() in one statement

SQL 服务器 : understanding default values

sql-server - 构造此数据以便递归 cte 可以读取它? (SQL服务器)

php - 指定 MySQL 加入

mysql - 简单且 Eloquent 地加入 laravel 5.3