嵌套的sql计数从两个计数查询到一个查询

时间:2012-04-17 07:24:17

标签: sql merge count

我正在努力将两个查询合并为一个(显然我不是一个sql大师;)

SELECT COUNT(orderid) AS TotalAmountOfOrders
FROM tableorder
WHERE (YEAR(orderDate) BETWEEN 2012 AND 2012)


SELECT COUNT(errorid) AS AmountOfErrorsOnOrders
FROM  tableError                      
WHERE (YEAR(errorDate) BETWEEN 2012 AND 2012)

问题是如果我只是将它们添加为

SELECT COUNT(orderid) AS ...,COUNT(errorid) AS ...
From tableorder inner join tableError

我没有得到总金额,只有错误的订单数量导致我如何把它们组合在一起。

那我怎么能在一个查询中得到两个计数呢?

3 个答案:

答案 0 :(得分:3)

您可以将其作为UNION:

SELECT COUNT(orderid) AS counted
FROM tableorder
WHERE (YEAR(orderDate) BETWEEN 2012 AND 2012)

UNION

SELECT COUNT(errorid) AS counted
FROM  tableError                      
WHERE (YEAR(errorDate) BETWEEN @Year1 AND @Year2)
GROUP BY SurName, FirstName;

然后第一行将是tableorder的计数,第二行将是tableError的计数。

答案 1 :(得分:0)

这会将值返回为两列。

SELECT 
  (
    SELECT COUNT(orderid)
    FROM tableorder
    WHERE (YEAR(orderDate) BETWEEN 2012 AND 2012)
  ) AS TotalAmountOfOrders,
  (
    SELECT COUNT(errorid)
    FROM  tableError                      
    WHERE (YEAR(errorDate) BETWEEN 2012 AND 2012)
  ) AS AmountOfErrorsOnOrders

我建议您根据间隔检查日期,而不是在列上应用函数。

SELECT 
  (
    SELECT COUNT(orderid)
    FROM tableorder
    WHERE orderDate >=  '20120101' AND OrderDate < '20130101'
  ) AS TotalAmountOfOrders,
  (
    SELECT COUNT(errorid)
    FROM  tableError                      
    WHERE errorDate >=  '20120101' AND errorDate < '20130101'
  ) AS AmountOfErrorsOnOrders

What makes a SQL statement sargable?

答案 2 :(得分:0)

试试这个:

SELECT COUNT(o.orderid), COUNT(e.errorid) AS TotalAmountOfOrders 
FROM tableorder o
INNER JOIN tableError e ON o.orderid = e.orderid
WHERE (YEAR(o.orderDate) BETWEEN 2012 AND 2012)
AND   (YEAR(e.errorDate) BETWEEN 2012 AND 2012)
GROUP BY o.orderid