2014-03-03 94 views
0

我想檢索以下示例中的數據。以下SQL將返回兩條記錄。SQL子查詢錯誤

SELECT -1 AS NUM 
FROM TABLE 
WHERE COMP_CODE = 'TEST' 
    AND (DETL_REMK = 'Rest Day' 
     OR SHFT_CODE = 'WK_PH') 
    AND RSRV_DATE_1 IS NOT NULL 
    AND RSRV_DATE_1 BETWEEN @TR_FR AND @TR_TO 
    AND EMPE_ID = 'TEST' 
GROUP BY EMPE_ID, 
     RSRV_DATE_1 

我想顯示下面。

ORG UNIT   EMPE_ID  FAM_NAME  TMS_TYPE  Qty 
----------------------------------------------------------------- 
''     ''    ''   Used   -1 
''     ''    ''   Used   -1 

所以,我正在努力做這樣的SQL語句。但是我得到了錯誤 「子查詢返回的值超過1,當子查詢跟隨=,!=,<,< =,>,> =或子查詢用作表達式時,這是不允許的。

如何構建正確的SQL。請幫幫我。提前致謝。

SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE, 
     ISNULL(CAST(
        (SELECT -1 AS NUM 
        FROM TABLE 
        WHERE COMP_CODE = 'TEST' 
        AND (DETL_REMK = 'Rest Day' 
          OR SHFT_CODE = 'WK_PH') 
        AND RSRV_DATE_1 IS NOT NULL 
        AND RSRV_DATE_1 BETWEEN @TR_FR AND @TR_TO 
        AND EMPE_ID = 'TEST' 
        GROUP BY EMPE_ID, RSRV_DATE_1)AS NVARCHAR(MAX)),0) QTY 

回答

1

你可以試試這個,而不是

SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE, -1 as QTY 
union all 
SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE, -1 as QTY 
4

如果你只是硬編碼子查詢外的值,你並不需要一個子查詢返回的2行,只是這樣做:

SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE, -1 AS QTY 
FROM TABLE 
WHERE COMP_CODE = 'TEST' 
    AND (DETL_REMK = 'Rest Day' 
     OR SHFT_CODE = 'WK_PH') 
    AND RSRV_DATE_1 IS NOT NULL 
    AND RSRV_DATE_1 BETWEEN @TR_FR AND @TR_TO 
    AND EMPE_ID = 'TEST' 
GROUP BY EMPE_ID, 
     RSRV_DATE_1 

這裏的問題是你沒有引用表中的任何列,只是使用它來產生大量的行。請分享完整的問題和代碼,因爲我確信這裏面還有更多你想問的問題。

+0

明白了。非常感謝。 –

0

您將需要前1添加到您的子查詢,從你所得到的錯誤,看起來像子查詢返回超過1行:

SELECT Top 1 -1 AS NUM 
FROM TABLE 
WHERE COMP_CODE = 'TEST' 
AND (DETL_REMK = 'Rest Day', 
OR SHFT_CODE = 'WK_PH') 
AND RSRV_DATE_1 IS NOT NULL 
AND RSRV_DATE_1 BETWEEN @TR_FR AND @TR_TO 
AND EMPE_ID = 'TEST' 
GROUP BY EMPE_ID, RSRV_DATE_1