I am very new to SQL and in fact, I am completely self taught. I currently have this query below which works to find (badly) 2 random support tickets by employee.
Right now, the query will ask the employees name and provide 2 results. Is there a way to have this provide 2 results for ALL employees?
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 :(得分:1)
I'm assuming you're using SQL Server based on syntax in question. You can use the ROW_NUMBER()
function inside a cte/subquery to generate a number for each row, using PARTITION BY
you can have the numbering start over for each member of a given set/group, in this case agent.LAST_NAME
, you can use that number to limit to two results per set/group:
;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