从两个表中选择第二个表中的第一行

时间:2014-11-26 10:57:03

标签: sql-server select sum

ACCOUNT(Name, Debit, Credit)

Name    | Debit  | Credit
=========================
Ram     | 2,000  | 2,000
Bheem   | 3,000  | 3,000
Soorya  | 2,500  | 1,750
John    | 3,500  | 2,500
Abdul   | 1,600  | 00000
Soorya  | 1,500  | 00000

CLIENTS(Name, ContactNumber)

Name   | ContactNumber
======================
Ram    | 900800
Bheem  | 900700
Soorya | 900600
John   | 900400
Abdul  | 900100
John   | No Value

SQL

SELECT Name, SUM(Debit), SUM(Credit) 
FROM ACCOUNT 
WHERE SUM(Credit)<>SUM(Debit) 
GROUP BY Name & ContactNumber 
FROM CLIENTS WHERE ACCOUNT.Name=CLIENTS.Name

如果客户端名称存在两次,则只应选择第一个ContactNumber。

预期结果:

Name   | SUM(Debit) | SUM(Credit)  | ContactNumber
==================================================
Soorya | 4,000      | 1,750        | 900600
John   | 3,500      | 2,500        | 900400
Abdul  | 1,600      | 0000         | 900100

如何排序此问题?

2 个答案:

答案 0 :(得分:1)

不确定这是否是最优雅的解决方案,但它对所提供的测试数据给出了正确的答案

WITH tmp
     AS (SELECT Name,
                Sum(Debit)  AS SumDebit,
                Sum(Credit) AS SumCredit
         FROM   accounts
         GROUP  BY Name)
SELECT a.Name,
       a.SumDebit,
       a.SumCredit,
       c.ContactNumber
FROM   tmp a,
       (SELECT Name,
               Max(ContactNumber) AS ContactNumber
        FROM   clients
        GROUP  BY Name) c
WHERE  a.Name = c.Name
       AND a.SumDebit <> a.SumCredit 

答案 1 :(得分:0)

尝试使用由名称字段链接的JOIN语句。

SELECT a.Name, SUM(a.Debit), SUM(a.Credit), DISTINCT(c.ContactNumber) FROM ACCOUNT a WHERE SUM(a.Credit) != SUM(a.Debit) INNER JOIN CLIENTS c ON a.Name = c.Name GROUP BY a.Name

希望它有所帮助。