SQL查询添加自定义值以基于不同的列值进行选择

时间:2014-11-06 13:57:09

标签: sql-server

我从子查询中选择了这个表:

Name    ResultType    TestID
Guy1    Result A      1
Guy1    Result B      1
Guy1    Result C      1
Guy1    Result A      2
Guy1    Result C      2
Guy1    Result B      3
Guy2    Result A      4
Guy2    Result C      4
Guy3    Result D      5
Guy3    Result A      6
--ETC

testID列表,获得的结果和用户名。 我希望能够在SELECT语句中得到它:

Name    ResultType    TestID    WhichTestNumberWasIt
Guy1    Result A      1         1
Guy1    Result B      1         1
Guy1    Result C      1         1 --The first distinct TestID for this user
Guy1    Result A      2         2
Guy1    Result C      2         2 --The second
Guy1    Result B      3         3 --And third
Guy2    Result A      4         1 --This is the first distinct TestID for this user
Guy2    Result C      4         1 
Guy3    Result D      5         1 --Again, same distinct TestID for another user
Guy3    Result A      6         2
--ETC

最好在SELECT语句中,因为这是来自()内部的JOIN的子查询,并且它已经相当大(我在这里省略了一堆列)。

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:3)

CREATE TABLE #tmp
(
    NAME VARCHAR(100),
    RT VARCHAR(50),
    testid INT
)

Insert into #tmp values('Guy1','Result A',1)
Insert into #tmp values('Guy1','Result B',1)
Insert into #tmp values('Guy1','Result C',1)
Insert into #tmp values('Guy1','Result A',2)
Insert into #tmp values('Guy1','Result C',2)
Insert into #tmp values('Guy1','Result B',3)
Insert into #tmp values('Guy2','Result A',4)
Insert into #tmp values('Guy2','Result C',4)
Insert into #tmp values('Guy3','Result D',5)
Insert into #tmp values('Guy3','Result A',6)


SELECT *,DENSE_RANK()   Over( PARTITION BY NAME ORDER BY TestID ASC) as Rank FROM #tmp

答案 1 :(得分:2)

您可以使用DENSE_RANK来获取此信息:

SELECT  Name,
        ResultType,
        TestID,
        TestNumber = DENSE_RANK() OVER(PARTITION BY Name ORDER BY TestID)
FROM    <Subquery>;

关于SQL小提琴的示例

完整示例

IF OBJECT_ID(N'tempdb..#T', 'U') IS NOT NULL DROP TABLE #T;

CREATE TABLE #T ([Name] VARCHAR(4), [ResultType] VARCHAR(8), [TestID] INT)
INSERT INTO #T ([Name], [ResultType], [TestID])
VALUES
    ('Guy1', 'Result A', 1),
    ('Guy1', 'Result B', 1),
    ('Guy1', 'Result C', 1),
    ('Guy1', 'Result A', 2),
    ('Guy1', 'Result C', 2),
    ('Guy1', 'Result B', 3),
    ('Guy2', 'Result A', 4),
    ('Guy2', 'Result C', 4),
    ('Guy3', 'Result D', 5),
    ('Guy3', 'Result A', 6);

SELECT  Name,
        ResultType,
        TestID,
        TestNumber = DENSE_RANK() OVER(PARTITION BY Name ORDER BY TestID)
FROM    #T
ORDER BY Name, TestID;