0

我有两个要组合的查询,以便我可以根据结果制作图表。结果必须非常具体,否则图表将无法正确显示信息

我在 Crystal Reports 11 中使用 MS SQL

以下是我正在寻找的结果。

         日期 发票类型 金额 
         2012/08 客户付款500
         2012/08 客户发票 1000
         2012/08 动平衡 1500
         2012/09 客户发票 400
         2012/09 动平衡 1900
         2012/10 兴趣 50
         2012/10 动平衡 1950

所以第一个查询返回以下结果

         日期 发票类型 金额 
         2012/08 客户付款500
         2012/08 客户发票 1000

         2012/09 客户发票 400

         2012/10 兴趣 50

第二个查询返回

         日期 发票类型 金额 

         2012/08 动平衡 1500
         2012/09 动平衡 1900
         2012/10 动平衡 1950

第二个查询很长而且很复杂,有一个 join 。加入这两个查询的最佳方法是什么,以便我有一列称为发票类型(因为图表基于此字段)

涵盖所有发票类型以及移动余额

4

2 回答 2

0

我假设Moving Balance结果集中行的位置很重要。

你可以这样做:

select date, invoice_type, amount
from
(
  select date, invoice_type, amount from query1
  union all
  select date, invoice_type, amount from query2
)
order by date, case invoice_type when 'Moving Balance' then 1 else 0 end

这首先将第二个查询的结果附加到第一个查询的结果,然后首先按日期重新排序结果列表,然后按发票类型重新排序,以使具有移动余额的行排在最后。


根据您给出的实际查询,它应该如下所示:

select date, invoice_type, amount
from
(
    SELECT
        CONVERT(VARCHAR(7),case_createddate, 111) AS Date,
        case_invoicetype as invoice_type,
        Sum(case_totalexvat) as amount
    FROM   cases AS ca
    WHERE  case_primaryCompanyid = 2174 and
    datediff(m,case_createddate,getDate()) 

    union all

    select
        CONVERT(VARCHAR(7),ca.case_createddate, 111) AS Date,
        'Moving Balance' as Invoice_Type,
        sum(mb.Amount) as Amount
    from
        cases as ca
        left join (
            select
                case_primaryCompanyId as ID,
                case_createdDate,
                case_TotalExVat as Amount
            from
                cases
        ) mb
        on ca. case_primaryCompanyId = mb.ID  
        and ca.case_createdDate >= mb.case_CreatedDate
    where
        ca.case_primaryCompanyId = 2174 and
        ca.case_createdDate > DATEADD(m, -12, current_timestamp)
    group by
        case_primaryCompanyId,
        CONVERT(VARCHAR(7),ca.case_createddate, 111)
    order by  ca.case_primaryCompanyid, CONVERT(VARCHAR(7),ca.case_createddate, 111)
)
order by date, case invoice_type when 'Moving Balance' then 1 else 0 end
于 2013-08-06T10:43:43.627 回答
0

您可以使用 Union 并且可以使用 Order by 子句

Select  * from (Query 1
Union
        Query 2
)  as a Order by a.Date Asc
于 2013-08-06T10:44:30.330 回答