简体   繁体   English

一个SQL查询,显示不需要的重排(连接3个表时)

[英]A SQL query showing unwanted resluts (when joining 3 tables)

I have been searching for a solution for this problem for quite sometime, i found some similar problems to mine but non of the proposed solution worked. 我已经为这个问题寻找解决方案已有一段时间了,我发现了一些与我类似的问题,但所提出的解决方案均无效。

I want to join these 3 tables. 我想加入这三个表。

(1) ADM (1) ADM

  • AID = Primary Key AID =主键
  • BedNo = int BedNo =整数

(2) ADMdeposite : (2) ADM存款

  • DID = Primary Key DID =主键
  • AID = Foreign key AID =外键
  • Dvalue = money Dvalue =金钱
  • Dvalue = Date Dvalue =日期

(3) Reservation : (3) 预约

  • ID = Primary Key ID =主键
  • AID = Foreign key AID =外键
  • Type = Nvchar Type = Nvchar
  • Value = Money Value =金钱
  • Pname = Nvarchar Pname = Nvarchar

I used this query 我用这个查询

SELECT        
    Reservation.AID, Reservation.type, Reservation.value, Reservation.pname, 
    ADMdeposit.Ddate, ADMdeposit.Dvalue
FROM
    ADM 
INNER JOIN
    ADMdeposit ON ADM.AID = ADMdeposit.AID 
INNER JOIN
    Reservation ON ADM.AID = Reservation.AID

I get the wanted results however the problem is, the ADMdeposite.Dvalue cell duplicates itself to the total number of Reservation.Type number of cells 我得到想要的结果,但问题是,在ADMdeposite.Dvalue细胞复制自身的总数Reservation.Type细胞数

Here is a print screen of the actual data in the ADMdeposite.Dvalue table 这是ADMdeposite.Dvalue表中实际数据的打印屏幕

在此处输入图片说明

Here is the result of the query: 这是查询的结果:

在此处输入图片说明

Here is the result I WANT: 这是我想要的结果:

在此处输入图片说明

After reading the comments and seeing that your goal is to calculate balances (deposits minus reservations), I would suggest summing the amounts of all deposits for each adm, do the same for the reservations, then join those 2 results together in order to calculate the balance : 阅读评论并看到您的目标是计算余额(存款减去预留金)后,我建议将每个adm的所有存款金额相加,对预留金进行相同的操作,然后将这两个结果加在一起以计算余额:

SELECT d.aid, 
       d.TotalDeposits, 
       r.TotalReservations, 
       d.TotalDeposits - r.TotalReservations as Balance 
FROM
(SELECT ADMdeposit.aid, SUM(ADMdeposit.dvalue) as TotalDeposits
FROM ADMdeposit GROUP BY ADMdeposit.aid) as d

INNER JOIN

(SELECT Reservation.AID, SUM(Reservation.value) as TotalReservations
FROM Reservation GROUP BY Reservation.AID) as r
ON d.AID = r.AID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM