2014-02-22 183 views
0

我正在使用SQL Server 2005.我試圖在一個合併兩行。SQL將兩行合併爲一個

需要幫助排除標識號和ApprovalCode NULL值。

SELECT DISTINCT CASE 
        WHEN (CONVERT(varchar(12), t1.referenceInfo)) like '1000%' THEN 
        (+ '"') + RTRIM(CONVERT(varchar(12), t1.referenceInfo)) + '"' 
        ELSE 
        '0' 
       END AS [ identity number ], 
       CASE 
        WHEN LEN(ISNUMERIC(CONVERT(varchar(12), t2.referenceInfo))) < 12 THEN 
        (+ '"') + RTRIM(CONVERT(varchar(12), t2.referenceInfo)) + '"' 
        WHEN (CONVERT(varchar(12), t2.referenceInfo)) LIKE '10%' THEN 
        (+ '"') + RTRIM(CONVERT(varchar(12), t2.referenceInfo)) + '"' 
        ELSE 
        '0' 
       END AS approvalcode 
    FROM dbo.GUEST_CHECK_LINE_ITEM_HIST t1 
INNER JOIN dbo.GUEST_CHECK_LINE_ITEM_HIST t2 
    ON t1.guestCheckID = t2.guestCheckID 
WHERE t1.guestCheckID = 78362401 
    AND (t1.referenceInfo) LIKE '1000%' 
    and (t2.referenceInfo) NOT LIKE '1000%' 
    --AND LEN(ISNUMERIC(CONVERT(varchar(12), t2.referenceInfo))) < 12 
GROUP BY t1.referenceInfo, t2.referenceInfo 

參考表如下 http://postimg.org/image/45q41bogf/

我想停放值等在身份號碼10000%和公園,小於12個數字的核準代碼的值。如果批准代碼少於12位,則爲空。

感激,如果能幫助我在這

結果 http://postimg.org/image/ngr9yzb6z/

回答

0

嘗試:

SELECT DISTINCT CASE 
        WHEN LEN(CONVERT(varchar(12), t1.referenceInfo)) > 11 THEN 
        (+ '"') + RTRIM(CONVERT(varchar(12), t1.referenceInfo)) + '"' 
        WHEN LEN(CONVERT(varchar(12), t2.referenceInfo)) > 11 THEN 
        (+ '"') + RTRIM(CONVERT(varchar(12), t2.referenceInfo)) + '"' 
        ELSE 
        '0' 
       END AS [ identity number ], 
       CASE 
        WHEN LEN(CONVERT(varchar(12), t1.referenceInfo)) < 12 THEN 
        (+ '"') + RTRIM(CONVERT(varchar(12), t1.referenceInfo)) + '"' 
        WHEN LEN(CONVERT(varchar(12), t2.referenceInfo)) < 12 THEN 
        (+ '"') + RTRIM(CONVERT(varchar(12), t2.referenceInfo)) + '"' 
        ELSE 
        '0' 
       END AS approvalcode 
    FROM dbo.GUEST_CHECK_LINE_ITEM_HIST t1 
INNER JOIN dbo.GUEST_CHECK_LINE_ITEM_HIST t2 
    ON t1.guestCheckID = t2.guestCheckID 
WHERE t1.guestCheckID = 78362401 
    AND t2.referenceInfo is not null 
    and t1.referenceInfo is not null 
GROUP BY t1.referenceInfo, t2.referenceInfo 

請注意,我更改了where子句的2行。它看起來像你使用「<> 0」,你可能打算使用「不爲空」。

0

嘗試添加

HAVING [identity number] is not null and approvalcode is not null 

末..

+0

我編輯了這個問題。請幫助傢伙。我需要在身份字段中以1000XXX開頭的所有數字,並以10XXXX的批准代碼開頭。並且在批准代碼中沒有任何以10返回null的數字開始。 – alexcctan