2014-11-21 75 views
0

我有一個SQL代碼在這裏我做了,我試圖找出如何使用情況和分組功能來代替文字值「所有「爲空值的彙總行。我也想過濾以AZ,MI,OH結尾的狀態結果。這是編寫代碼的正確方法嗎?使用情況和分組功能,與空彙總行代替文字值值

SELECT AccountDescription AS Account, VendorState, SUM(invoicelineitemamount) as LineItemSum 
    CASE 
     WHEN ISNULL THEN '*ALL*' 
    END 
FROM ap.dbo.Vendors 
JOIN ap.dbo.Invoices 
    ON Vendors.VendorID = Invoices.VendorID 
JOIN ap.dbo.invoicelineitems 
    ON Invoices.InvoiceID = InvoiceLineItems.InvoiceID 
JOIN ap.dbo.GLAccounts 
    ON InvoiceLineItems.AccountNo = GLAccounts.AccountNo 
WHERE VendorState IN ('AZ', 'MI', 'OH') 
GROUP BY AccountDescription, VendorState WITH CUBE 

回答

0

GROUPING函數返回0,如果該列值從數據來,1,如果該列值是由CUBE操作生成的NULL。

與case語句的選擇會是這樣

Select 
    CASE WHEN (GROUPING(AccountDescription) = 1) THEN 'ALL' 
     ELSE AccountDescription 
    END AS Account 
    CASE WHEN (GROUPING(VendorState) = 1) THEN 'ALL' 
     ELSE VendorState 
    END AS VendorState, 
    SUM(invoicelineitemamount) as LineItemSum 
+0

什麼設置分組等於1嗎?我只是從書中複製它,它沒有提供解釋它爲什麼這樣做。 – 2014-11-21 00:44:20

+0

@Lisa謝霆鋒,分組功能通過多維數據彙總行返回null值,則返回1 – radar 2014-11-21 01:02:54

+0

@RADAR SQL Server 2012的肯定支持CUBE,它尚未刪除(未在2014年任)。 ROLLUP在功能上並不等同 - CUBE爲所有組合生成彙總行,ROLLUP不會。 – jpw 2014-11-21 01:26:21

0

首先,WITH CUBE語法在SQL Server的未來版本被刪除,不應該被使用; GROUP BY CUBE()應該這樣做(或者你可能想要ROLLUP)。

二,將NULL值更改爲ALL您可以使用grouping()函數或isnull()

第三,如果你VendorState只是兩個字母則是:

WHERE VendorState IN ('AZ','MI', 'OH') 

是你想要的,但如果它是一個較長的字符串(如Portland, OR),並在最後的狀態代碼,做這樣的樣本代碼如下:

SELECT 
    CASE WHEN GROUPING(AccountDescription) = 1 THEN 'ALL' ELSE AccountDescription END AS Account, 
    ISNULL(AccountDescription, 'ALL') AS Account, 
    ISNULL(VendorState, 'ALL') AS VendorState, 
    SUM(invoicelineitemamount) as LineItemSum 
FROM ap.dbo.Vendors 
JOIN ap.dbo.Invoices 
    ON Vendors.VendorID = Invoices.VendorID 
JOIN ap.dbo.invoicelineitems 
    ON Invoices.InvoiceID = InvoiceLineItems.InvoiceID 
JOIN ap.dbo.GLAccounts 
    ON InvoiceLineItems.AccountNo = GLAccounts.AccountNo 
--WHERE VendorState IN ('AZ','MI', 'OH') 
WHERE 
    VendorState LIKE '%AZ' OR 
    VendorState LIKE '%MI' OR 
    VendorState LIKE '%OH' 
GROUP BY CUBE(AccountDescription, VendorState) 

查看reference documentation for GROUP BY瞭解更多信息。

在一個側面說明,你可能要熟悉你可以用它來不必重複長表標識符,例如表的別名:

FROM ap.dbo.Vendors v 
JOIN ap.dbo.Invoices i ON v.VendorID = i.VendorID 
+0

非常感謝您的澄清,您可以接受答案。它看起來像添加isnull子句確實將空值替換爲'ALL' – 2014-11-21 01:54:39