简体   繁体   English

如何合并此SQL Server查询?

[英]How to merger this sql server query?

I have this query 我有这个查询

select count(*) as COUNT_A, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name] 
where Sertifikat_Nomor IS NOT NULL
group by datepart(yyyy, [Tgl_Perolehan])

and this 和这个

select count(*) as COUNT_B, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name] 
where Sertifikat_Nomor IS NULL
group by datepart(yyyy, [Tgl_Perolehan])

The difference is only IS NOT NULL and IS NULL and the result is 区别只是IS NOT NULLIS NULL ,结果是

+---------+--------+ | COUNT_A | year | +----------+--------+ | 12 | 1991 | | 15 | 1993 | | 24 | 1998 | +----------+--------+

I want make like this 我要这样

+---------+---------+--------+ | COUNT_A | COUNT_B | year | +----------+---------+--------+ | 12 | 23 | 1991 | | 15 | 33 | 1993 | | 24 | 13 | 1998 | +----------+---------+--------+

and I try like this 我尝试这样

select (select count(*) as COUNT_A, datepart(yyyy, [Tgl_Perolehan]) as [year] 
from [table_name]
where Sertifikat_Nomor IS NOT NULL
group by datepart(yyyy, [Tgl_Perolehan])), 
(select count(*) as COUNT_B, datepart(yyyy, [Tgl_Perolehan]) as [year]
from [table_name] 
where Sertifikat_Nomor IS NULL
group by datepart(yyyy, [Tgl_Perolehan]))

But didn't fix my problem. 但是并没有解决我的问题。 I have use CASE WHEN , but still didn't fix the problem. 我已经使用CASE WHEN ,但是仍然无法解决问题。 How to merge and fix their? 如何合并和修复它们? Thanks. 谢谢。

Try this- 尝试这个-

SELECT
SUM(CASE WHEN ertifikat_Nomor IS NOT NULL THEN 1 ELSE 0 END) AS COUNT_A,
SUM(CASE WHEN Sertifikat_Nomor IS NULL THEN 1 ELSE 0 END)AS COUNT_B,
DATEPART(yyyy, [Tgl_Perolehan]) AS [year]
FROM[table_name] 
GROUP BY DATEPART(yyyy, [Tgl_Perolehan])

Try this using co-related subquery 使用相关子查询尝试一下

SELECT   Datepart(yyyy, o.[Tgl_Perolehan]) AS [Tgl_Perolehan] , 
         ( 
                SELECT Count(*) 
                FROM   [table_name] i 
                WHERE  i.<somid> = o.<somid> 
                AND    i.sertifikat_nomor  IS NOT NULL ) AS AS count_a , 
         ( 
                SELECT count(*) 
                FROM   [table_name] ii 
                WHERE  ii.<somid> = o.<somid> 
                AND    ii.sertifikat_nomor IS NULL) AS AS count_b 
FROM     [table_name] o 
GROUP BY datepart(yyyy,o.[Tgl_Perolehan])

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

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