结合SQL Server查询

时间:2012-04-27 13:20:18

标签: sql sql-server

我正在使用SQL Server,我有两个表,我想组合成一个可以用来填充gridview的查询。

表1 dbo.Work
UID(PK,int)
Tech_Ticket(int)
RMA_Ticket(int)
地区(nchar10)
完成(nchar10)
FA(nchar10)
代理人(nvarchar50)
跟踪(nvarchar50)
Date_Added(日期)
Date_Updated(日期)

表2 dbo.Orders
UID(PK,int)
订单(int)
代理人(nvarchar50)
票(int)
备注(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] 

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

1 个答案:

答案 0 :(得分: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]