如何在不复制表单内部联接表的情况下选择记录

时间:2016-03-17 08:33:11

标签: sql-server

从此查询中,如何获取没有重复值的记录。 我需要获取值,如果表c中的名称和表c中的帐户应该在日期字段最大时查看。

SELECT
      a.name
    , a.dates
    , b.da
    , a.id
    , b.client
    , b.[Address]
    , b.[City]
    , b.[State]
    , b.dot
    , b.Score
    , b.Pay
    , b.code
    , b.[Country]
FROM a
INNER JOIN c ON a.Account = c.Account
INNER JOIN b ON [a].name = b.name
WHERE c.users = 00
    AND b.Act = 1
ORDER BY a.dates

2 个答案:

答案 0 :(得分:0)

使用DISTINCT

SELECT DISTINCT
      a.name
    , a.dates
    , b.da
    , a.id
    , b.client
    , b.[Address]
    , b.[City]
    , b.[State]
    , b.dot
    , b.Score
    , b.Pay
    , b.code
    , b.[Country]
FROM a
INNER JOIN c ON a.Account = c.Account
INNER JOIN b ON [a].name = b.name
WHERE c.users = 00
    AND b.Act = 1
ORDER BY a.dates

答案 1 :(得分:0)

如何使用CTE?

with CTE_duplicate 
as
(SELECT 
  a.name
, a.dates
, b.da
, a.id
, b.client
, b.[Address]
, b.[City]
, b.[State]
, b.dot
, b.Score
, b.Pay
, b.code
, b.[Country]
, row_number() over ( partition by a.name
, a.dates
, b.da
, a.id
, b.client
, b.[Address]
, b.[City]
, b.[State]
, b.dot
, b.Score
, b.Pay
, b.code
, b.[Country]   order by a.name
, a.dates
, b.da
, a.id
, b.client
, b.[Address]
, b.[City]
, b.[State]
, b.dot
, b.Score
, b.Pay
, b.code
, b.[Country] ) as rownumber
FROM a
INNER JOIN c ON a.Account = c.Account
INNER JOIN b ON [a].name = b.name
WHERE c.users = 00
AND b.Act = 1
) select * from  CTE_duplicate where rownumber=1 order by dates;