小编典典

合并SQL Server查询

sql

我正在使用SQL Server,并且我有两个表,我想合并为一个查询,用它来填充gridview。

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]

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


阅读 163

收藏
2021-04-14

共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]
2021-04-14