2016-07-11 84 views
0

我對SQL很陌生,事實上,我完全自學。我目前有這個查詢下面的工作,找到(嚴重)由員工2隨機支持門票。SQL查詢返回多個員工的2個結果

現在,查詢會詢問員工姓名並提供2個結果。有沒有辦法讓所有員工都能得到2個結果?

SELECT 
     TOP 2 CONVERT (
      DATE, 
      SD_REQUEST.END_DATE_UT 
     ) AS 'Close Date', 
     SD_REQUEST.RFC_number AS 'Ticket', 
     agent.LAST_NAME AS 'Agent', 
     AM_DOMAIN.NAME_EN AS 'Company', 
     EE.LAST_NAME AS 'Recipient', 
     RR.LAST_NAME AS 'Requestor', 
     catpath.SD_CATALOG_PATH_EN 
    FROM 
     SD_REQUEST 
    LEFT JOIN AM_EMPLOYEE AS agent ON agent.EMPLOYEE_ID = SD_REQUEST.OWNER_ID 
    LEFT JOIN AM_EMPLOYEE AS EE ON EE.EMPLOYEE_ID = SD_REQUEST.RECIPIENT_ID 
    LEFT JOIN AM_EMPLOYEE AS RR ON RR.EMPLOYEE_ID = SD_REQUEST.REQUESTOR_ID 
    LEFT JOIN SD_CATALOG_PATH AS catpath ON catpath.SD_CATALOG_ID = SD_REQUEST.SD_CATALOG_ID 
    LEFT JOIN AM_DOMAIN ON AM_DOMAIN.DOMAIN_ID = EE.DEFAULT_DOMAIN_ID 
    WHERE 
     agent.LAST_NAME = 'insert name here' 
    AND CONVERT (
     datetime, 
     SD_REQUEST.END_DATE_UT, 
     101 
    ) BETWEEN (Getdate() - 8) 
    AND (Getdate() - 2) 
    ORDER BY 
     NEWID() 
+0

您使用的是哪個版本的SQL Server?問題標籤爲MySQL。 –

+0

刪除'agent.LAST_NAME ='在此處插入名稱' AND',它會給你一切。 – arcee123

回答

1

我假設您正在使用基於語法問題的SQL Server。您可以使用cte/subquery中的ROW_NUMBER()函數爲每行生成一個數字,使用PARTITION BY您可以爲給定集合/組中的每個成員開始編號,在此例中爲agent.LAST_NAME,可以使用該數字來限制到每個集合/組的兩個結果:

;with cte AS (
     SELECT CONVERT (DATE,SD_REQUEST.END_DATE_UT) AS 'Close Date', 
       SD_REQUEST.RFC_number AS 'Ticket', 
       agent.LAST_NAME AS 'Agent', 
       AM_DOMAIN.NAME_EN AS 'Company', 
       EE.LAST_NAME AS 'Recipient', 
       RR.LAST_NAME AS 'Requestor', 
       catpath.SD_CATALOG_PATH_EN, 
       ROW_NUMBER() OVER(PARTITION BY agent.LAST_NAME ORDER BY NEWID()) AS RN 
      FROM 
       SD_REQUEST 
      LEFT JOIN AM_EMPLOYEE AS agent ON agent.EMPLOYEE_ID = SD_REQUEST.OWNER_ID 
      LEFT JOIN AM_EMPLOYEE AS EE ON EE.EMPLOYEE_ID = SD_REQUEST.RECIPIENT_ID 
      LEFT JOIN AM_EMPLOYEE AS RR ON RR.EMPLOYEE_ID = SD_REQUEST.REQUESTOR_ID 
      LEFT JOIN SD_CATALOG_PATH AS catpath ON catpath.SD_CATALOG_ID = SD_REQUEST.SD_CATALOG_ID 
      LEFT JOIN AM_DOMAIN ON AM_DOMAIN.DOMAIN_ID = EE.DEFAULT_DOMAIN_ID 
     WHERE CONVERT (datetime,SD_REQUEST.END_DATE_UT,101) BETWEEN (Getdate() - 8) AND (Getdate() - 2) 
     ) 
SELECT * 
FROM cte 
WHERE RN <= 2 
+0

這工作很好。謝謝! – Mattrajotte