0

我正在努力寻找一种将两个查询合并为一个的方法(显然我不是 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

我没有得到总金额,而只有由于我将它们组合在一起的方式而导致错误的订单数量。

那么我怎样才能在一个查询中同时获得两个计数呢?

4

3 回答 3

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 的计数。

于 2012-04-17T07:30:07.563 回答
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

是什么让 SQL 语句可搜索?

于 2012-04-17T07:31:02.070 回答
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
于 2012-04-17T07:31:14.493 回答