我有两个问题。我想合并一个表和两列。
SELECT COUNT(IsApproved) as CountNotApproved
FROM Erp_OrderReceipt
WHERE IsApproved = 0
和
SELECT COUNT(IsApproved) as CountApproved
FROM Erp_OrderReceipt
WHERE IsApproved = 1
答案 0 :(得分:3)
您可以使用条件聚合:
SELECT COUNT(case when IsApproved = 0 then 0 end) as CountNotApproved,
COUNT(case when IsApproved = 1 then 1 end) as CountApproved
FROM Erp_OrderReceipt;
这是有效的,因为聚合函数会忽略NULL
个值。对于与条件不匹配的所有行,CASE
的结果为NULL
。
如果您的DBMS支持此功能,您还可以使用ANSI SQL filter
子句:
SELECT COUNT(*) FILTER (where IsApproved = 0) as CountNotApproved,
COUNT(*) FILTER (where IsApproved = 1) as CountApproved
FROM Erp_OrderReceipt
答案 1 :(得分:0)
您可以使用Union和group
SELECT SUM(CountApproved) CountApproved,
SUM(CountNotApproved) CountNotApproved
FROM
(
SELECT
0 as CountApproved,
COUNT(IsApproved) as CountNotApproved
FROM Erp_OrderReceipt where IsApproved=0
UNION
SELECT
COUNT(IsApproved) as CountApproved,
0 as CountNotApproved
FROM Erp_OrderReceipt where IsApproved=1
) u