1

我正在使用 SQL Server,我有两个表,我想组合成一个查询,我可以用它来填充网格视图。

Table1 dbo.Work
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)

Table2 dbo.Orders
UID(PK, int)
Order (int)
Agent (nvarchar50)
Ticket (int)
Notes (nvarchar50)

现在我将它们设置为两个单独的查询和两个单独的表。

查询1:

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] 

查询2:

SELECT [Agent] 
  SUM(CASE WHEN [Date] BETWEEN @startDate AND @endDate THEN 1 ELSE 0 END) AS 'Orders'
  FROM Orders 
  GROUP BY [Agent] 

有没有办法将这两个查询合并为一个?

4

1 回答 1

1

你可以JOIN。假设Work是主表,应该是这样的:

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]
于 2012-04-27T13:28:36.533 回答