将两个SQL查询合并为一个

时间:2015-12-16 17:58:54

标签: sql tsql sql-server-2012

SELECT 
    party.name, leger.partyId, leger.descriptions, leger.cashBySum, 
    leger.cashByName, leger.date 
FROM  
    leger 
INNER JOIN 
    party ON leger.partyId = party.id 
WHERE 
    (leger.partyId = @partyID) 
    AND (CAST(leger.date AS date) BETWEEN @fromdate AND @todate) 
ORDER BY 
    leger.date 
CROSS JOIN 
    SELECT 
        (CASE WHEN (SUM(cashBySum) > SUM(cashByName)) THEN N'جمع' 
              WHEN (SUM(cashBySum) < SUM(cashByName)) THEN N' بنام' 
              ELSE '' END) AS balancetype, 
        SUM(cashBySum) - SUM(cashByName) AS balance, 
        ABS(SUM(cashBySum) - SUM(cashByName)) AS blc
    FROM leger
    WHERE (partyId = @partyTypes) AND (date < @fromdate)

如何将此查询合并到单个查询并在RDLC报告中使用?

我想获得最后一笔余额,然后通过减去最后一笔余额来计算日期余额,以便生成报告。

2 个答案:

答案 0 :(得分:0)

您可以将查询水平与交叉联接组合在一起。也许这就是你的意思?

WITH q1 as (
    SELECT
        party.name, leger.partyId, leger.descriptions,
        leger.cashBySum, leger.cashByName, leger.date
    FROM
        leger INNER JOIN party ON leger.partyId = party.id
    WHERE
        leger.partyId = @partyID AND CAST(leger.date AS date) BETWEEN @fromdate AND @todate
), q2 as (
    SELECT
        CASE
            WHEN SUM(cashBySum) > SUM(cashByName) THEN N'جمع' 
            WHEN SUM(cashBySum) < SUM(cashByName) THEN N' بنام'
            ELSE ''
        END AS balancetype,
        SUM(cashBySum) - SUM(cashByName) AS balance,
        ABS(SUM(cashBySum) - SUM(cashByName)) AS blc
    FROM leger
    WHERE partyId = @partyTypes AND date < @fromdate
)
SELECT q1.*, q2.*
FROM q1 CROSS JOIN q2
ORDER BY leger.date

使用ORDER BY表示至少在第一个查询中有多行。第二个聚合成一个组,所以它应该是我预期的一行;但是,如果第二行也有多行,那么在这种情况下,我不确定交叉连接是否真的是你想要的。

联合将要求您匹配两个查询之间的列上的数字和类型。这可能就是为什么它不适合你。

答案 1 :(得分:0)

SELECT 
    party.name, leger.partyId, leger.descriptions, leger.cashBySum, 
    leger.cashByName, leger.date 
FROM  
    leger 
INNER JOIN 
    party ON leger.partyId = party.id 
          AND  leger.partyId = @partyID 
          AND (CAST(leger.date AS date) BETWEEN @fromdate AND @todate) 

CROSS JOIN 
  ( SELECT 
        (CASE WHEN (SUM(cashBySum) > SUM(cashByName)) THEN N'جمع' 
              WHEN (SUM(cashBySum) < SUM(cashByName)) THEN N' بنام' 
              ELSE '' END) AS balancetype, 
        SUM(cashBySum) - SUM(cashByName) AS balance, 
        ABS(SUM(cashBySum) - SUM(cashByName)) AS blc
    FROM leger
    WHERE (partyId = @partyTypes) AND (date < @fromdate) 
  )
ORDER BY 
    leger.date