从第一个表中选择所有值,从第二个表中选择第一个值

时间:2015-03-20 20:59:15

标签: sql sql-server tsql

enter image description here

我想从代码表中的 Users 和min dateUsed中选择所有值。我怎么能这样做?

我试过这个:

    SELECT u.firstName, u.lastName, u.fbId, q.dateUsed, u.codesLeft
  FROM Users u
  inner join Code q on  u.Id = q.userId

但是它从“代码”和“用户”表中选择了所有值。

P.S。添加distinct无效

4 个答案:

答案 0 :(得分:1)

  

添加distinct无效

根据经验,DISTINCT有助于单列SELECT。有多个列,您需要选择大枪#34; - GROUP BY条款。

为了使其工作,您需要确保您选择的每个项目都是GROUP BY列,或者具有合适的聚合函数:

SELECT u.firstName, u.lastName, u.fbId, MIN(q.dateUsed) as dateUsed, u.codesLeft
FROM Users u
INNER JOIN Code q ON u.Id = q.userId
GROUP BY u.firstName, u.lastName, u.fbId, u.codesLeft

答案 1 :(得分:1)

尝试使用ROW_NUMBER函数

的此查询
SELECT *
FROM (
    SELECT u.Id AS userId, u.firstName, u.lastName, c.codeVal, ROW_NUMBER() OVER(PARTITION BY c.userId ORDER BY c.dateUsed) AS RowNum
    FROM dbo.Users u INNER JOIN db.Code c ON u.Id = c.userId
) x
WHERE x.RowNum = 1

答案 2 :(得分:1)

标量子查询

SELECT u.firstName,
u.lastName,
u.fbId,
(SELECT TOP 1 dateUsed
    FROM Code as q WHERE u.Id = q.userId
    ORDER BY dateUsed ASC),
u.codesLeft
FROM Users u

或CTE

;WITH SEQ as (
SELECT userId, MIN(DateUsed) as FirstDate, MAX(DateUsed) as lastDate
FROM Code GROUP BY userID)

SELECT... u.*, q.FirstDate, q.LastDate
FROM Users as u
JOIN SEQ as q ON u.ID = q.userID

答案 3 :(得分:0)

如果您想从代码表中查看更多内容而不仅仅是日期,您可以在联接中使用相关子查询:

SELECT  u.firstName, u.lastName, u.fbId, q.dateUsed, u.codesLeft,
        q.codeVal, q.ipUsed
FROM    Users u
join    Code q
    on  q.userId = u.Id
    and q.dateUsed =(
        select  Min( dateUsed )
        from    Code
        where   userID = q.userID );