我目前拥有的伪代码是
费用+ CostTax = CostActual
但是,我需要它:
成本+税 - totalSumDiscounts = CostActual
我在连接3个表的SQL Select语句中计算成本+税= CostActual。
SELECT dbo.XMP_EventUsers.ID, dbo.XMP_EventUsers.EventID, dbo.XMP_EventUsers.UserID,
CONVERT(VARCHAR(20),dbo.XMP_EventUsers.DateCreated, 100)
AS DateCreated, CONVERT(VARCHAR, dbo.XMP_Event.Cost, 1) AS Cost, dbo.Users.FirstName, dbo.Users.LastName,
dbo.XMP_Event.Cost + dbo.XMP_Event.CostTax - dbo.XMP_EventUsers.Paid AS Outstanding,
dbo.XMP_Event.Cost + dbo.XMP_Event.CostTax AS CostActual
FROM dbo.XMP_Event INNER JOIN
dbo.XMP_EventUsers ON dbo.XMP_Event.ID = dbo.XMP_EventUsers.EventID INNER JOIN
dbo.Users ON dbo.XMP_EventUsers.UserID = dbo.Users.UserID
另一张表记录了应用于总费用的折扣。此查询总计了要应用的折扣。
SELECT UserID, SUM([Amount]) AS Amount
FROM [dbo].[XMP_EventPromoUsers]
GROUP BY UserID
如何将第二个结果加入到第一个结果中,以便折扣总数是每个记录的select语句中最终成本的最小值?
感谢您的帮助!
-R
以下答案1的结果示例
查询1返回:
ID|EventID|UserID|DateCreated|Cost|FirstName|LastName|Outstanding|CostActual|FinalValue|
51|14-----|41----|Aug 11 2011|0.00|John-----|Smith---|-120-------|0.00------|-10-------|
查询2
UserID-|Amount----|
41-----|10--------|
96-----|30--------|
答案 0 :(得分:3)
SELECT
dbo.XMP_EventUsers.ID, dbo.XMP_EventUsers.EventID, dbo.XMP_EventUsers.UserID,
CONVERT(VARCHAR(20),dbo.XMP_EventUsers.DateCreated, 100) AS DateCreated,
CONVERT(VARCHAR, dbo.XMP_Event.Cost, 1) AS Cost,
dbo.Users.FirstName, dbo.Users.LastName,
dbo.XMP_Event.Cost + dbo.XMP_Event.CostTax - dbo.XMP_EventUsers.Paid AS Outstanding,
dbo.XMP_Event.Cost + dbo.XMP_Event.CostTax AS CostActual,
dbo.XMP_Event.cost + dbo.XMP_Event.CostTax - Users2.Amount AS FinalValue
FROM
dbo.XMP_Event
INNER JOIN dbo.XMP_EventUsers
ON dbo.XMP_Event.ID = dbo.XMP_EventUsers.EventID
INNER JOIN dbo.Users
ON dbo.XMP_EventUsers.UserID = dbo.Users.UserID
INNER JOIN (SELECT UserID, SUM([Amount]) AS Amount
FROM [dbo].[XMP_EventPromoUsers]
GROUP BY UserID) Users2
ON dbo.Users.UserID = Users2.UserID