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

时间:2017-12-12 09:19:41

标签: sql 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  

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

Processed列将显示特定月份的员工流程数,例如3月将来自表2

Not Processed会显示TotalProcessed列值之间的差异

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

2 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:1)

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

<强> Results

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

SQL Fiddle

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)
;