使用0作为默认计数值

时间:2012-02-14 07:57:13

标签: asp.net sql sql-server

我有一个查询(部分内容),如下所示,当我的GridView加载此查询时,那些没有IssCountUsedCount值的行将为空。如何为这些记录设置这些列的默认0值?

SELECT
    CASE
    WHEN @SortByTypeCode = 1 THEN ROW_NUMBER() OVER(ORDER BY vt.Code)
    WHEN @SortByTypeName = 1 THEN ROW_NUMBER() OVER(ORDER BY vt.Name)               
    WHEN @SortByTypeIssued = 1 THEN ROW_NUMBER() OVER(ORDER BY count(X.IssCount))
    WHEN @SortByTypeUsed = 1 THEN ROW_NUMBER() OVER(ORDER BY count(Y.UsedCount ))
    ELSE ROW_NUMBER() OVER(ORDER BY vt.AutoID)
    END AS RowNum
    ,vt.AutoID
    ,vt.Code
    ,X.IssCount as Issued
    ,Y.UsedCount as Used
INTO #tmp_Results --Dont Change This
FROM VoucherType vt
LEFT JOIN (
    SELECT VoucherType_AutoID,COUNT(VoucherNo) IssCount
    FROM Voucher
    WHERE VoidedBy IS NULL AND VoidedOn IS NULL 
    GROUP BY VoucherType_AutoID     
) X ON vt.AutoID = X.VoucherType_AutoID
LEFT JOIN (
    SELECT V.VoucherType_AutoID, COUNT(VUsed.AutoID) UsedCount
    FROM voucherUsedLog VUsed
    INNER JOIN Voucher V ON VUsed.Voucher_AutoID = V.AutoID
    WHERE VUsed.VoidedBy IS NULL AND VUsed.VoidedOn IS NULL
    GROUP BY V.VoucherType_AutoID
) Y
ON vt.AutoID = Y.VoucherType_AutoID 

2 个答案:

答案 0 :(得分:3)

试试这种方式..

ISNULL(X.IssCount,0) as Issued
,ISNULL(Y.UsedCount,0) as Used

答案 1 :(得分:3)

您可以将COALESCE包裹在X.IssCountY.UsedCount周围,使它们为0,如下所示:

,COALESCE(X.IssCount,0) as Issued
,COALESCE(Y.UsedCount,0) as Used