2016-01-11 58 views
0

我有我的代碼行:刪除包含null進行交叉連接

SELECT Y.shipdate[Sent date], 
Rate_ = 'price' + Z.Which, 
Bill_ = 'bill' + Z.Which, 
       Rate = CASE Z.Which 
        WHEN '1' THEN price1 
        WHEN '2' THEN price2 
        WHEN '3' THEN price3 
        WHEN '4' THEN price4 
        WHEN '5' THEN price5 
        WHEN '6' THEN price6 END, 
       Bill = CASE Z.Which 
        WHEN '1' THEN bill1 
        WHEN '2' THEN bill2 
        WHEN '3' THEN bill3 
        WHEN '4' THEN bill4 
        WHEN '5' THEN bill5 
        WHEN '6' THEN billr6 END,   
    Y.duedate[Due Date], Y.recvdate[Received] 
    FROM tra Y 
    CROSS JOIN (SELECT '1' union ALL SELECT '2' UNION ALL SELECT '3' UNION ALL SELECT '4' UNION ALL SELECT '5' UNION ALL SELECT '6') Z (Which) 
    WHERE name = 'test' 

與輸出:

Sent Date     Rate_ Bill_ Rate Bill Due Date     Received 
2015-12-22 00:00:00.000  price1 bill1 0.55 300.00 2015-12-16 00:00:00.000 2015-12-01 00:00:00.000 
2015-12-22 00:00:00.000  price2 bill2 0.04 2.00 2015-12-16 00:00:00.000 2015-12-01 00:00:00.000 
2015-12-22 00:00:00.000  price3 bill3 0.07 43.00 2015-12-16 00:00:00.000 2015-12-01 00:00:00.000 
2015-12-22 00:00:00.000  price4 bill4 0.00 0.00 2015-12-16 00:00:00.000 2015-12-01 00:00:00.000 
2015-12-22 00:00:00.000  price5 bill5 0.00 0.00 2015-12-16 00:00:00.000 2015-12-01 00:00:00.000 
2015-12-22 00:00:00.000  price6 bill6 0.00 0.00 2015-12-16 00:00:00.000 2015-12-01 00:00:00.000 

我想要的輸出,將只在價格和賬單值顯示行。根據我的示例,輸出中應該只有3行。謝謝。

+1

發表您的預期輸出。如果可能的話也提供一些樣本數據。 – pedram

回答

0

試試這個

where name = 'test' 
and CASE Z.Which 
     WHEN '1' THEN price1 
     WHEN '2' THEN price2 
     WHEN '3' THEN price3 
     WHEN '4' THEN price4 
     WHEN '5' THEN price5 
     WHEN '6' THEN price6 
    END <> 0.00 

CROSS JOIN產生兩個表的笛卡爾乘積。與其他JOIN運算符不同,它不允許指定聯接子句。但在你的情況下,你正在使用過濾器來消除行。在這種情況下最好使用Natural Join

+0

哇謝謝!有用。 – 404notfound

+0

另一個問題,你有關於如何刪除rate_和bill_列的想法嗎?謝謝。 – 404notfound

+0

只是從選擇它刪除這些列將工作正常。 – saikumarm

1

也可以通過其他方式來實現,但這是最通用的,並且可以在大多數RDBMS系統中工作。使用你的主要查詢作爲子查詢,並給where條件

SELECT * FROM (
SELECT Y.shipdate[Sent date], 
Rate_ = 'price' + Z.Which, 
Bill_ = 'bill' + Z.Which, 
       Rate = CASE Z.Which 
        WHEN '1' THEN price1 
        WHEN '2' THEN price2 
        WHEN '3' THEN price3 
        WHEN '4' THEN price4 
        WHEN '5' THEN price5 
        WHEN '6' THEN price6 END, 
       Bill = CASE Z.Which 
        WHEN '1' THEN bill1 
        WHEN '2' THEN bill2 
        WHEN '3' THEN bill3 
        WHEN '4' THEN bill4 
        WHEN '5' THEN bill5 
        WHEN '6' THEN bill6 END,   
    Y.duedate[Due Date], Y.recvdate[Received] 
    FROM tra Y 
    CROSS JOIN (SELECT '1' union ALL SELECT '2' UNION ALL SELECT '3' UNION ALL SELECT '4' UNION ALL SELECT '5' UNION ALL SELECT '6') Z (Which) 
    WHERE name = 'test') TMP_TAB 
WHERE RATE <> 0 AND BILL <> 0 
+0

這也適用!謝謝! – 404notfound