SQL Server计数查询将结果与总计进行比较

时间:2014-10-29 10:55:56

标签: sql-server sql-server-2008

我试图返回完全拒绝的不同发票的数量。发票可以包含多个订单项。如果发票的订单项包含原因' '和另一个' 拒绝'然后它没有完全被拒绝,不应该被计算在内。

我想要的结果如下

Client     | No. of Invoices Fully Rejected
-------------------------------------------
Schogotten | 1
Maiken     | 2

从逻辑上讲,我相信我会返回发票数量,其中订单项的数量等于每张发票拒绝原因的发票数。

以下是SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE Tmp (
  id int NOT NULL,
  client varchar (24) NOT NULL,
  invoice varchar(5) NOT NULL,
  statusid int NOT NULL,
  reason varchar (24)
)


INSERT INTO Tmp (id, client, invoice, statusid, reason) 
VALUES (12345, 'Schogotten', 'ABC12', -99, 'Rejected')
, (12346, 'Schogotten', 'ABC12', -99, 'None')
, (12347, 'Schogotten', 'ABC12', 10001, 'ReadyToPay')
, (12348, 'Schogotten', 'ABC11', -99, 'Rejected')
, (12349, 'Schogotten', 'ABC10', -99, 'None')
, (12350, 'Maiken', 'ABC13', -99, 'Rejected')
, (12351, 'Maiken', 'ABC14', 9006, 'ReadyToPay')
, (12351, 'Maiken', 'ABC14', -99, 'None')
, (12352, 'Maiken', 'ABC15', -99, 'Rejected');

查询1

SELECT Client
, COUNT(Invoice)
FROM Tmp
WHERE Reason = 'Rejected'
GROUP BY Client

Results

|     CLIENT | COLUMN_1 |
|------------|----------|
|     Maiken |        2 |
| Schogotten |        2 |

1 个答案:

答案 0 :(得分:1)

我会使用子查询查找相关的发票,然后使用外部查询按客户分组:

select client,COUNT(*) from (
  select client,invoice
  from Tmp
  group by client,invoice
  having MIN(reason) = MAX(reason) and
  MIN(reason) = 'Rejected'
) t
group by client

希望逻辑很容易阅读 - 子查询只是找到所有行具有相同值(MIN(reason) = MAX(reason))的发票,其中原因是Rejected然后我们只计算它们。