使用实际记录验证摘要计数列

时间:2017-09-11 16:04:26

标签: sql sql-server

我在用户表'total_approved_sales'中有一个列,其中包含状态为'已批准'的所有销售的计数。

对于某些用户,我的total_approved_sales列可能已关闭,因此我想列出所有用户,其total_approved_sales不等于销售表中的总和

USER
- total_approved_sales

sales
- userId
- STATUS

表格布局如下:

{{1}}

如何查询计数已关闭的用户?

2 个答案:

答案 0 :(得分:1)

加入聚合派生表:

select 
    u.UserId
  , u.total_approved_sales
  , a.recount
from user u
  left join (
    select s.userid, recount = count(*)
    from sales s
    where s.status = 'approved'
    group by s.userid
  ) a
    on u.userid = a.userid
where u.total_approved_sales <> isnull(a.recount,0)

给出以下测试设置:

create table [user] (userid int, total_approved_sales int);
insert into [user] values (0,0),(1,1),(2,1)
create table sales (userid int, [status] varchar(32))
insert into sales values (1,'approved'),(1,'pending'),(2,'approved'),(2,'approved')

rextester演示:http://rextester.com/TPQZ17719

返回:

+--------+----------------------+---------+
| UserId | total_approved_sales | recount |
+--------+----------------------+---------+
|      2 |                    1 |       2 |
+--------+----------------------+---------+

答案 1 :(得分:0)

您可以使用APPLY运算符实现此目的:

select *
    from [user] u
    outer apply (select count(*) from sales where userId=u.id and status='approved') sales(cnt)
    where u.total_approved_sales <> sales.cnt;