比较两个SQL SELECT的值

时间:2015-06-09 10:11:26

标签: sql sql-server tsql

在以下两个SELECT语句中,我想比较这两个语句的输出,以获得金额不匹配的IDs

第一个语句中的GROUP BYSUM似乎使事情变得复杂:

SELECT CreditAHID,
SUM(Debit) as CCDebit,
SUM(Credit) as CCCredit,
FROM FS_2015_June.dbo.CCs
GROUP BY CreditAHID

SELECT ID as CreditAHID,
JuneDebit as AHDebit,
JuneCredit as AHCredit,
FROM FS_2015_2016.dbo.AHs

有没有办法将它们组合成这样的东西?

SELECT ID ... WHERE (CCDebit != AHDebit) OR (CCCredit != AHCredit)

5 个答案:

答案 0 :(得分:1)

您可以尝试使用CTE:

WITH cte as (
SELECT CreditAHID,
SUM(Debit) as CCDebit,
SUM(Credit) as CCCredit,
FROM FS_2015_June.dbo.CCs
GROUP BY CreditAHID
), cte2 as (
SELECT ID as CreditAHID,
JuneDebit as AHDebit,
JuneCredit as AHCredit,
FROM FS_2015_2016.dbo.AHs)

SELECT * FROM cte
UNION
SELECT * FROM cte2
WHERE CCDebit <> AHDebit and CCCredit <> AHCredit

答案 1 :(得分:0)

请尝试以下查询:

SELECT
    ResultSet1.*
    , ResultSet2.*
FROM (
    SELECT CreditAHID
        ,SUM(Debit) AS CCDebit
        ,SUM(Credit) AS CCCredit
    FROM FS_2015_June.dbo.CCs
    GROUP BY CreditAHID
    ) ResultSet1
INNER JOIN (
    SELECT ID AS CreditAHID
        ,JuneDebit AS AHDebit
        ,JuneCredit AS AHCredit
    FROM FS_2015_2016.dbo.AHs
    ) ResultSet2 ON ResultSet1.CreditAHID = ResultSet2.CreditAHID
WHERE ResultSet1.CCDebit <> ResultSet2.AHDebit
    AND ResultSet1.CCCredit <> ResultSet2.AHCredit

此查询将返回两个结果的组合,其中CreditAHID在两个结果中匹配,并且CCDebitCCCredit分别不等于AHDebitAHCredit

答案 2 :(得分:0)

您可以简单地写为:

select T1.CreditAHID as [CCs], T2.CreditAHID as [AHs]
from (
SELECT CreditAHID,
SUM(Debit) as CCDebit,
SUM(Credit) as CCCredit,
FROM FS_2015_June.dbo.CCs
GROUP BY CreditAHID) T1
full Join (
SELECT ID as CreditAHID,
JuneDebit as AHDebit,
JuneCredit as AHCredit,
FROM FS_2015_2016.dbo.AHs) T2 
on T1.CreditAHID = T2.CreditAHID
where T1.CCDebit <> AHDebit 
and T1.CCCredit <> T2.AHCredit

答案 3 :(得分:0)

您可以像这样使用EXCEPT

SELECT CreditAHID,
SUM(Debit) as CCDebit,
SUM(Credit) as CCCredit,
FROM FS_2015_June.dbo.CCs
GROUP BY CreditAHID
EXCEPT
SELECT ID as CreditAHID,
JuneDebit as AHDebit,
JuneCredit as AHCredit,
FROM FS_2015_2016.dbo.AHs

注意,EXCEPT返回左输入查询中不是由右输入查询输出的不同行。因此,如果第二个查询包含更多行,则应首先引用它。

答案 4 :(得分:0)

您可以尝试使用旧的不存在 这样的:

SELECT CreditAHID, SUM(Debit) as CCDebit, SUM(Credit) as CCCredit
   FROM FS_2015_June.dbo.CCs c
GROUP BY CreditAHID
having not exists 
       (SELECT 1
          FROM FS_2015_2016.dbo.AHs
         where ID = c.CreditAHID and 
        (Sum(c.Debit) = JuneDebit or Sum(c.Credit) = JuneCredit))

以下是我在SQL Fiddle中所做的一个例子:http://sqlfiddle.com/#!6/d02b8/1/0