I am using SQL Server and I have two tables and I would like to combine into one query that I can use to fill a gridview.
UID (PK, int)
Tech_Ticket (int)
RMA_Ticket (int)
Region (nchar10)
Completed (nchar10)
FA (nchar10)
Agent (nvarchar50)
Tracking (nvarchar50)
Date_Added (date)
Date_Updated (date)
UID (PK, int)
Order (int)
Agent (nvarchar50)
Ticket (int)
Notes (nvarchar50)
Right now I have them setup as two separate queries and two separate tables.
SELECT [Agent],
SUM(CASE WHEN [Date_Added] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'New ',
SUM(CASE WHEN [Date_Updated] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'Worked',
SUM(CASE WHEN [Completed] = 'yes' AND [Date_Updated] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'Completed',
SUM(CASE WHEN [Failure_Analysis] = 'yes' AND [Date_Updated] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'FA'
FROM Work
GROUP BY [Agent]
SELECT [Agent]
SUM(CASE WHEN [Date] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'Orders'
FROM Orders
GROUP BY [Agent]
Is there a way to combine these two queries into one?
You can JOIN
them. Assuming that Work
is the main table, it should be like this:
SELECT A.*, B.Orders
FROM ( SELECT [Agent],
SUM(CASE WHEN [Date_Added] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'New',
SUM(CASE WHEN [Date_Updated] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'Worked',
SUM(CASE WHEN [Completed] = 'yes' AND [Date_Updated] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'Completed',
SUM(CASE WHEN [Failure_Analysis] = 'yes' AND [Date_Updated] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'FA'
FROM Work
GROUP BY [Agent]) A
LEFT JOIN (SELECT [Agent]
SUM(CASE WHEN [Date] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'Orders'
FROM Orders
GROUP BY [Agent]) B
ON A.[Agent] = B.[Agent]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.