从“UserInfo”表中选定的UserId中选择表“ContactInfo”中重复的UserId的最大数量

时间:2016-03-11 03:53:20

标签: mysql sql sql-server

我的查询是这样的(Credit @Felix Pamittan)

   CREATE TABLE #UserInfo(UserId INT, Name VARCHAR(10));
   CREATE TABLE #ContactInfo(Id INT, UserId INT, Email VARCHAR(20), Mobile VARCHAR(6));

   INSERT INTO #UserInfo VALUES (1, 'Sandeep'), (2, 'James'), (3, 'Vishal');
   INSERT INTO #ContactInfo VALUES (1, 1, 'e1@somemail.com', '111111'), (2, 1, 'e2@somemail.com', '222222'), (3, 3, 'v1@somemail.com', '010101');

   DECLARE @sql NVARCHAR(MAX)
   SELECT @sql = 
  'SELECT
  u.UserId
 ,u.Name' + CHAR(10)
 SELECT @sql = @sql +
 ',MAX(CASE WHEN t.rn = ' + CONVERT(VARCHAR(10), rn) +' THEN t.Email END) AS                  
' + QUOTENAME('Email' + CONVERT(VARCHAR(10), rn)) + CHAR(10) +
' , MAX(CASE WHEN t.rn = ' + CONVERT(VARCHAR(10), rn) +' THEN t.Mobile END) AS ' 
    + QUOTENAME('Mobile' + CONVERT(VARCHAR(10), rn)) + CHAR(10)
 FROM (
SELECT DISTINCT
    rn = ROW_NUMBER() OVER(PARTITION BY UserId ORDER BY Id)
FROM ContactInfo
     )t
 -- Add filter here for ROW_NUMBER, e.g. starting ffrom the start row to end row
 WHERE rn BETWEEN 1 AND 2

SELECT @sql = @sql +
 'FROM UserInfo u
LEFT JOIN (
 SELECT *,
    rn = ROW_NUMBER() OVER(PARTITION BY UserId ORDER BY Id)
FROM ContactInfo
 )t
ON t.UserId = u.UserId
-- Add filter here for ROW_NUMBER, e.g. starting from the start row to end row
AND rn BETWEEN 1 AND 2
GROUP BY u.UserId, u.Name
ORDER BY u.UserId, u.Name offset 1 rows FETCH NEXT 2 ROWS ONLY'

PRINT @sql
EXEC(@sql)

我的输出就像这样enter image description here 现在我需要从我的结果中删除Email2和Mobile2。为此,我需要从#UserInfo表

中选择的UserId中的#ContactInfo中计算ROW_NUMBER OF UserId

你可以在这里获得Demo

0 个答案:

没有答案