繁体   English   中英

在组By或where子句中使用子查询SQL Server

[英]Using Subquery in group By or where clause SQL Server

我要创建摘要报告。

以下是表格结构

表格1 :

EmpID |  Code |  Name | Category
------+-------+-------+----------
1     | 1008M | ABC   | 1
2     | 1039E | XYZ   | 1
3     | 1040E | TYS   | 2
4     | 1041E | TYS   | 2

表2:

EmpID |  Month     |  Net Pay
------+------------+----------
1     | March      | 1000     
2     | March      | 3000  
4     | March      | 3000  

所需的输出应显示单个类别中有多少员工(“总计”列)

“已Processed列将显示特定月份(例如3月)的员工处理数量,该数量来自表2

Not Processed将显示“ Total和“已Processed列值之间的差异

Category | Total |  Processed | Not Processed
---------+-------+------------+--------------
1        | 2     | 2          | 0
2        | 2     | 1          | 1

我尝试使用以下查询,但无法正常工作。

select 
    B.Category,
    processcount = (select count(*) from Table2 A 
                    where A.Companyid = 2 
                      and A.Month = 'March' 
                      and A.Employeeid = b.Id) 
from 
    Table1 B 
where 
    B.Companyid = 2 and empstatus = 1 
group by 
    Category

尝试这个

with cte
as
(
select
t1.category,
Cnt = case when t2.empid is null then 0
          else 1 end
from table1 t1
left join table2 t2
on t1.empid = t2.empid and t2.Month='March'
)
select
Category,
Total = count(1),
Processed = sum(cnt),
NotProcessed=sum(case when cnt=0 then 1 else 0 end)
from cte
group by category
select
       category, count(*) Total, sum(oa.n) Processed, count(*) - sum(oa.n) Not_Processed
from table1
outer apply (
    select max(1) from table2 
    where table2.empid = table1.empid
    and table2.month = 'March'
    -- + other conditions here if needed
    ) oa (n)
group by 
       category

结果

| category | Total | Processed | Not_Processed |
|----------|-------|-----------|---------------|
|        1 |     2 |         2 |             0 |
|        2 |     2 |         1 |             1 |

SQL小提琴

CREATE TABLE Table1
    ([EmpID] int, [Code] varchar(5), [Name] varchar(3), [Category] int)
;

INSERT INTO Table1
    ([EmpID], [Code], [Name], [Category])
VALUES
    (1, '1008M', 'ABC', 1),
    (2, '1039E', 'XYZ', 1),
    (3, '1040E', 'TYS', 2),
    (4, '1041E', 'TYS', 2)
;


CREATE TABLE Table2
    ([EmpID] int, [Month] varchar(5), [Net Pay] int)
;

INSERT INTO Table2
    ([EmpID], [Month], [Net Pay])
VALUES
    (1, 'March', 1000),
    (2, 'March', 3000),
    (4, 'March', 3000)
;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM