我的两个查询分开工作,但当我在另一个内部嵌套时,它不再有效

时间:2017-10-24 03:38:00

标签: mysql nested-query

我的第一个问题是:

SELECT 
SUM(CASE WHEN (Transactions.RegFunction = '1' AND Transactions.RegYear = "2017") THEN RegAmt END) AS GroupCurrsumFee, 
SUM(CASE WHEN (Transactions.RegFunction = '1' AND Transactions.RegYear = "2017") THEN Transactions.LMSCAmt END) AS IndCurrsumFee
FROM AllTransactions

我的第二个问题是:

SELECT GroupAmt 
FROM GroupFees
WHERE
'2016-11-01' BETWEEN BeginDate AND EndDate
AND RegYear = "2016"
AND GROUPID = "14"
AND RegFunction = 1;

当我运行该查询时,它返回以下内容:

|  GroupAmt  |
|   5.00     |

当我将第二个查询嵌套在第一个查询内部时,它可以在列别名中返回该数据,但它不会显示。我将两个查询合并并编写如下:

SELECT
SUM(CASE WHEN (Transactions.RegFunction = '1' AND Transactions.RegYear = "2017") THEN RegAmt END) AS GroupCurrsumFee, 
    SUM(CASE WHEN (Transactions.RegFunction = '1' AND Transactions.RegYear = "2017") THEN Transactions.LMSCAmt END) AS IndCurrsumFee,
(SELECT GroupAmt FROM GroupFees
    WHERE
    '2016-11-01' BETWEEN BeginDate AND EndDate
    AND RegYear = "2016"
    AND GROUPID = "14"
    AND RegFunction = 1) AS GroupFee
FROM AllTransactions

1 个答案:

答案 0 :(得分:0)

改为使用联接。鉴于查询可能返回NULL的可能性,我建议使用始终为true的连接条件的左连接。 (有点“hacky”。​​)注意,不能保证子查询只返回一行。如果它确实你的整体结果可能不是你所期望的那样。

SELECT SUM(CASE 
        WHEN (
                Transactions.RegFunction = '1'
                AND Transactions.RegYear = "2017"
                )
            THEN RegAmt
        END) AS GroupCurrsumFee
, SUM(CASE 
        WHEN (
                Transactions.RegFunction = '1'
                AND Transactions.RegYear = "2017"
                )
            THEN Transactions.LMSCAmt
        END) AS IndCurrsumFee
   , GroupFee.GroupAmt
FROM AllTransactions
LEFT JOIN (
    SELECT GroupAmt
    FROM GroupFees
    WHERE '2016-11-01' BETWEEN BeginDate
            AND EndDate
        AND RegYear = '2016'
        AND GROUPID = '14'
        AND RegFunction = 1
    ) AS GroupFee on 1=1