时间:2016-07-05 22:20:41

标签: sql sql-server sql-server-2012 common-table-expression

以下是我每月检索报告以获取付费和未付预订的查询

SELECT tbc.tbcId
    ,tbc.tbcName
    ,(
        SELECT COUNT(bb.bbId)
        FROM MyBooking bb
        WHERE bb.tbcId = tbc.tbcId
            AND bb.bbIsPayed = 1
            AND Year(bb.bbDate) = '2016' --proc parameter @year
            AND Month(bb.bbDate) = '7' --proc parameter @month
        ) AS PaidCount
    ,(
        SELECT SUM(CASE 
                    WHEN bb.bbVAT = 1
                        THEN (bb.bbPrice / 100) * 80
                    ELSE bb.bbPrice
                    END)
        FROM MyBooking bb
        WHERE bb.tbcId = tbc.tbcId
            AND bb.bbIsPayed = 1
            AND Year(bb.bbDate) = '2016' --proc parameter @year
            AND Month(bb.bbDate) = '7' --proc parameter @month
        ) AS PaidAmount
    ,(
        SELECT COUNT(bb.bbId)
        FROM MyBooking bb
        WHERE bb.tbcId = tbc.tbcId
            AND bb.bbIsPayed <> 1
            AND Year(bb.bbDate) = '2016' --proc parameter @year
            AND Month(bb.bbDate) = '7' --proc parameter @month
        ) AS UnpaidCount
    ,(
        SELECT SUM(CASE 
                    WHEN bb.bbVAT = 1
                        THEN (bb.bbPrice / 100) * 80
                    ELSE bb.bbPrice
                    END)
        FROM MyBooking bb
        WHERE bb.tbcId = tbc.tbcId
            AND bb.bbIsPayed <> 1
            AND Year(bb.bbDate) = '2016' --proc parameter @year
            AND Month(bb.bbDate) = '7' --proc parameter @month
        ) AS UnPaidAmount
FROM BookingCategories tbc
WHERE tbc.tbcIncludeReport = 1
    AND tbc.tbcId IN (
        SELECT DISTINCT con.tbcId
        FROM CategoryXTags con
        WHERE (
                con.ttId = 26
                OR con.ttId = 23
                OR con.ttId = 24
                )
        )
ORDER BY tbc.tbcName ASC;

我必须在特定的时间段内运行,例如2016年1月至2016年8月。

截至目前,我通过传递@year和@month变量在循环中运行它。

是否可以通过@FromDate和@Todate并在同一查询中生成每个月的报告?我无法用SQL来思考这个问题。

1 个答案:

答案 0 :(得分:1)

未经测试,但我认为会缩短您的流程

Declare @Date1 Date = '2016-01-01'
Declare @Date2 Date = '2016-08-31'

Select Period       = EOMonth(bb.bbDate)
      ,tbc.tbcId
      ,tbc.tbcName
      ,PaidCount    = sum(case when bb.bbIsPayed=1 then 1 else 0 end)
      ,PaidAmount   = sum(case when bb.bbIsPayed=1 and 1bb.bbVAT = 1 Then (bb.bbPrice / 100) * 80 ELSE bb.bbPrice end)
      ,UnpaidCount  = sum(case when bb.bbIsPayed<>1 then 1 else 0 end)
      ,UnPaidAmount = sum(case when bb.bbIsPayed <> 1 and bb.bbVAT = 1 Then (bb.bbPrice / 100) * 80 ELSE bb.bbPrice end)
 From  BookingCategories tbc
 Join  MyBooking bb on (bb.bbId = tbc.tbcId)
 Where tbc.tbcIncludeReport = 1
   and tbc.tbcId IN (26,26,24)
   and bb.bbDate between @Date1 and @Date2
 Group By 
       EOMonth(bb.bbDate)
      ,tbc.tbcId
      ,tbc.tbcName
 Order By 1,tbc.tbcName ASC