1

私は SQL Server を使用しており、2 つのテーブルがあり、グリッドビューを埋めるために使用できる 1 つのクエリに結合したいと考えています。

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)

現在、2 つの個別のクエリと 2 つの個別のテーブルとしてセットアップしています。

クエリ 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] 

これら 2 つのクエリを 1 つに結合する方法はありますか?

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 に答える