2013-03-19 59 views
1

我已經編寫了一個查詢來從聯合檢索結果。但它顯示了兩行的結果並將空列留爲0.但是我需要一行結果而不需要零。任何人都可以請幫我。下面是我的查詢下面給出我已經寫了兩個部分>>>從聯合查詢中獲取單個行的字段

SELECT COUNT(gi.id) AS no_of_group , 
     0 AS no_of_borrower 
FROM group_info AS gi 
WHERE gi.domain_status_id = 1 
    AND gi.group_status_id = 1 
    AND gi.group_creation_date <= '2013-01-31' 
    AND gi.project_info_id = 'BI0000000000000000000001' 
    AND gi.branch_info_id = 'BI0000000000000000000363' 
UNION 
SELECT 0 AS no_of_group , 
     COUNT(outerlat.member_info_id) AS no_of_borrower 
FROM 
    (SELECT lat.member_info_id, 
      MAX(lat.id) AS max_member_id 
    FROM loan_account_transaction AS lat 
    WHERE lat.project_info_id = 'BI0000000000000000000001' 
    AND lat.country_id = 1 
    AND lat.domain_status_id = 1 
    AND lat.office_info_id = 'BI0000000000000000000363' 
    AND lat.transaction_date <= '2013-01-31' 
    GROUP BY lat.member_info_id) AS tempData 
INNER JOIN loan_account_transaction AS outerlat ON (tempData.max_member_id = outerlat.id) 
WHERE outerlat.loan_status_id IN(1,3,4,5) 
+0

這是MySQL還是SQL Server? – 2013-03-19 12:25:38

回答

2

您可以選擇每列作爲一個子查詢,而不是,因爲這樣的:

SELECT 
    (SELECT COUNT(gi.id) 
    FROM group_info AS gi 
    WHERE gi.domain_status_id = 1 AND 
     gi.group_status_id = 1 AND 
     gi.group_creation_date <= '2013-01-31' AND 
     gi.project_info_id = 'BI0000000000000000000001' AND 
     gi.branch_info_id = 'BI0000000000000000000363') AS no_of_group 
    ,(SELECT COUNT(outerlat.member_info_id) 
    FROM 
     (SELECT lat.member_info_id, MAX(lat.id) AS max_member_id FROM loan_account_transaction AS lat 
     WHERE lat.project_info_id = 'BI0000000000000000000001' AND lat.country_id = 1 AND lat.domain_status_id = 1 
     AND lat.office_info_id = 'BI0000000000000000000363' AND lat.transaction_date <= '2013-01-31' 
    GROUP BY lat.member_info_id) AS tempData 
    INNER JOIN loan_account_transaction AS outerlat 
    ON (tempData.max_member_id = outerlat.id) 
    WHERE outerlat.loan_status_id IN(1,3,4,5)) AS no_of_borrower 
+0

這是有用的,但我有其他很多的聯盟價值,我必須在一個字段中顯示將工作 – 2013-03-19 12:41:33

+0

如果您有來自每個子查詢的多個列,您可以使用子查詢作爲一個表。 – aaroncatlin 2013-03-19 12:48:22

+1

感謝人作爲子查詢它的工作非常感謝 – 2013-03-19 13:15:34

0

可以使用CTE(公共表達式) -

With AllData as 
(SELECT 
    Count -- etc 
     AS no_of_group, 
    0 AS no_of_borrower 
UNION ALL 
    SELECT 
    0 AS no_of_group, 
    COUNT -- etc 
     AS no_of_borrower 
) 
SELECT 
    Sum(no_of_group) as no_of_group, 
    Sum(no_of_borrower) as no_of_borrower 
FROM AllData 
+0

我不明白它請你能表達一些 – 2013-03-19 12:44:03

+0

Common Table Expressions值得了解 - http://msdn.microsoft.com/en-us/library/ms190766%28v = SQL.105%29.aspx – 2013-03-19 13:03:24

相關問題