如何使用Case语句

时间:2017-08-28 14:46:12

标签: sql-server

我有3个SQL SELECT语句,如何使用CASE语句并获得单个SELECT语句。

我的查询是:

-- Earned Points

SELECT CAST(p.TransactionDT AS DATE) as 'Date' , p.PointsItemValue as 'Point Value', pi.PointsItemDesc
    FROM PointsTransaction p
    JOIN PointsTransactionType ptt ON ptt.PointsTransactionTypeID = p.PointsTransactionTypeID
    JOIN PointsItem pi ON pi.PointsItemID = p.PointsItemID
    JOIN Person pe ON pe.PersonID = p.PersonID
    JOIN School s on s.SchoolID = p.SchoolID
    WHERE p.PersonID = @PersonID AND pe.SchoolID = @schoolid AND CAST(p.TransactionDT AS DATE) BETWEEN @FromDate AND @ThruDate and p.PointsTransactionTypeID = 1  and p.IsVoid = 0

-- Redeemed Points

SELECT CAST(p.TransactionDT AS DATE) as 'Date' , p.PointsItemValue as 'Point Value', pi.PointsItemDesc
    FROM PointsTransaction p
    JOIN PointsTransactionType ptt ON ptt.PointsTransactionTypeID = p.PointsTransactionTypeID
    JOIN PointsItem pi ON pi.PointsItemID = p.PointsItemID
    JOIN Person pe ON pe.PersonID = p.PersonID
    JOIN School s on s.SchoolID = p.SchoolID
    WHERE p.PersonID = @PersonID AND pe.SchoolID = @schoolid AND CAST(p.TransactionDT AS DATE) BETWEEN @FromDate AND @ThruDate and p.PointsTransactionTypeID = 2 and p.IsVoid = 0

-- Voided Points    

SELECT CAST(p.TransactionDT AS DATE) as 'Date' , p.PointsItemValue as 'Point Value', pi.PointsItemDesc
    FROM PointsTransaction p
    JOIN PointsTransactionType ptt ON ptt.PointsTransactionTypeID = p.PointsTransactionTypeID
    JOIN PointsItem pi ON pi.PointsItemID = p.PointsItemID
    JOIN Person pe ON pe.PersonID = p.PersonID
    JOIN School s on s.SchoolID = p.SchoolID
    WHERE p.PersonID = @PersonID AND pe.SchoolID = @schoolid AND CAST(p.TransactionDT AS DATE) BETWEEN @FromDate AND @ThruDate and p.IsVoid = 1

2 个答案:

答案 0 :(得分:0)

正如您所想,您可以轻松地使用案例表达式来完成此操作。此外,不推荐使用字符串作为列别名的FWIW。

SELECT CAST(p.TransactionDT AS DATE) as 'Date' 
    , p.PointsItemValue as 'Point Value'
    , pi.PointsItemDesc
    , case when p.PointsTransactionTypeID = 1  and p.IsVoid = 0 then 'Earned Points'
            when p.PointsTransactionTypeID = 2 and p.IsVoid = 0 then 'Redeemed Points'
            when p.IsVoid = 1 then 'Voided Points'
        end
FROM PointsTransaction p
JOIN PointsTransactionType ptt ON ptt.PointsTransactionTypeID = p.PointsTransactionTypeID
JOIN PointsItem pi ON pi.PointsItemID = p.PointsItemID
JOIN Person pe ON pe.PersonID = p.PersonID
JOIN School s on s.SchoolID = p.SchoolID
WHERE p.PersonID = @PersonID 
    AND pe.SchoolID = @schoolid 
    AND CAST(p.TransactionDT AS DATE) BETWEEN @FromDate AND @ThruDate 
    and 
    (
        p.PointsTransactionTypeID = 1  and p.IsVoid = 0
        OR
        p.PointsTransactionTypeID = 2 and p.IsVoid = 0
        OR
        p.IsVoid = 1
    )

答案 1 :(得分:0)

使用条件聚合:

factory/service