sql [sql]从连接表中选择一个子行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql [sql]从连接表中选择一个子行相关的知识,希望对你有一定的参考价值。

-- USERS TABLE --
-- ID	Email				FirstName		LastName		Institution				Position	Phone		RegisterDateTime		UUID
-- 1	sarpay@gmail.com		Sarpay			Oner			The Tada and Shorts Company		Position 1	714 434 4344	2011-01-01 00:00:00.000		234234-23423-234
-- 2	mertay@gmail.com		Mertay			Oner			Mandarin Cantonese KungFu		Position 2	904 344 3434	2012-01-01 00:00:00.000		2344-4564-756756
-- 3	ozlemozmen5@yahoo.com.tr	Ozlem			Ozmen			Moraly Disturbed Individuals Lab	Position 3	989 434 3434	2013-01-01 00:00:00.000		5343-45345-34534
-- 4	sarpay@hotmail.com		sarpay			oner			lkjlkjlkj				ljklkjl		909 909 9090	2013-01-01 00:00:00.000		23232


-- TESTS TABLE --
-- ID	UserID		TimerID		TimerType	RunDateTime
-- 1	1		1		preset		2014-01-01 00:00:00.000
-- 2	1		2		custom		2014-01-02 00:00:00.000
-- 3	2		1		custom		2014-01-05 00:00:00.000
-- 4	*3		*2		*preset		2014-02-02 00:00:00.000
-- 5	*4		*2		*preset		2014-01-01 00:00:00.000
-- 6	*4		*2		*preset		2014-04-04 00:00:00.000


CREATE PROCEDURE [dbo].[getUsersByTimerId]

	@TimerID AS INT,
	@TimerType AS NVARCHAR(10)

AS

BEGIN

	SELECT
		[U].*,
		[viewTests].[RunDateTime] [TestDateTime]
		
	FROM 
		[Users] [U]
		INNER JOIN 
			(
				SELECT
					[T].[UserID],
					[T].[TimerID],
					MAX([T].[RunDateTime]) [RunDateTime]
				FROM
					[Tests] [T]
				WHERE
					[T].[TimerType] = @TimerType
					AND
					[T].[TimerID] = @TimerID
				GROUP BY
					[T].[UserID],
					[T].[TimerID]
			) AS [viewTests]
			ON [viewTests].[UserID] = [U].[ID]
			
		ORDER BY
			[viewTests].[RunDateTime] DESC
		
END


EXEC	@return_value = [dbo].[getUsersByTimerId]
		@TimerID = 2,
		@TimerType = N'preset'


-- QUERY RESULT --
-- ID	Email				FirstName	LastName	Institution				Position	Phone		RegisterDateTime		UUID			TestDateTime
-- 4	sarpay@hotmail.com		sarpay		oner		lkjlkjlkj				ljklkjl		909 909 9090	2013-01-01 00:00:00.000		23232			2014-04-04 00:00:00.000
-- 3	ozlemozmen5@yahoo.com.tr	Ozlem		Ozmen		Moraly Disturbed Individuals Lab	Position 3	989 434 3434	2013-01-01 00:00:00.000		5343-45345-34534	2014-02-02 00:00:00.000

以上是关于sql [sql]从连接表中选择一个子行的主要内容,如果未能解决你的问题,请参考以下文章

如何从SQL表中选择特定行并在SQL Server中连接多个表?

3 个表和一个子查询的 SQL 连接问题

为 SQL 连接选择单个(随机)行

如何在 Oracle SQL 中选择一个子字符串直到一个特定的字符?

用于从连接表中进行选择的 T-SQL 查询,其中有可变数量的参数?

sql - 从多个连接表中获取匹配行数