2016-07-26 197 views
0

我有兩個查詢。我想合併一個表格和兩列。合併兩列SQL查詢

SELECT COUNT(IsApproved) as CountNotApproved 
FROM Erp_OrderReceipt 
WHERE IsApproved = 0 

SELECT COUNT(IsApproved) as CountApproved 
FROM Erp_OrderReceipt 
WHERE IsApproved = 1 

回答

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 
0

您可以使用聯盟和組對該

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 
+0

語法錯誤... – jarlh

+0

修正去除語法錯誤 – Juan