我有一系列相关的表格。
TRANSACTION_TYPE
Transaction_ID(主要)
TRANSACTION_AMOUNT
Transaction_Type
交易
Transaction_ID(主要)
时间戳
购买
TRANSACTION_ID
的Item_ID
Purchase_ID(主要)
物品
的Item_ID
CLIENT_ID
我需要根据时间戳和client_id
选择transaction_type行我的查询如下:
SELECT
SUM(tt.Transaction_Amount)
FROM
ItemTracker_dbo.Transaction_Type tt
JOIN
ItemTracker_dbo.Transaction t
ON
tt.Transaction_ID = t.Transaction_ID
JOIN
ItemTracker_dbo.Purchase p
ON
p.Transaction_ID = tt.Transaction_ID
JOIN
ItemTracker_dbo.Item i
ON
i.Item_ID = p.Item_ID
WHERE
t.TimeStamp >= $start AND t.TimeStamp <= $end
AND
tt.Transaction_Format IN ('cash', 'credit')
AND
i.Client_ID = $client_ID
问题:
如果客户在交易中购买了多个商品,则transaction_id将在Purchase表中包含多个行。因此,连接正在为transaction_id重复transaction_amount,该事务在购买时有多行。
有没有办法将UNIQUE
应用于此次查询的购买行?
还有其他方法可以解决购买中的多行问题吗?
或者我是否需要重新评估数据库的架构?
如果有任何其他信息有用,请告诉我。
答案 0 :(得分:1)
使用子查询。
SELECT SUM(tt.Transaction_Amount)
FROM ItemTracker_dbo.Transaction_Type tt
WHERE tt.Transaction_ID IN
(SELECT t.Transaction_ID FROM
ItemTracker_dbo.Transaction t
JOIN
ItemTracker_dbo.Purchase p
ON
p.Transaction_ID = t.Transaction_ID
JOIN
ItemTracker_dbo.Item i
ON
i.Item_ID = p.Item_ID
WHERE
t.TimeStamp >= $start AND t.TimeStamp <= $end
AND
tt.Transaction_Format IN ('cash', 'credit')
AND
i.Client_ID = $client_ID)
答案 1 :(得分:1)
需要使用内部选择,如下所示:
select sum(tt.Transaction_Amount)
from ItemTracker_dbo.Transaction_Type tt
inner join ItemTracker_dbo.Transaction t ON tt.Transaction_ID = t.Transaction_ID
inner join
(select distinct(transaction_id) as transID
from Purchase as P
inner join Item as I on P.Item_ID = I.Item_ID
where I.Client_ID = $client_ID) blah
on t.Transaction_ID = blah.transID
t.TimeStamp >= $start AND t.TimeStamp <= $end
AND
tt.Transaction_Format IN ('cash', 'credit')
答案 2 :(得分:0)
我认为你必须使用子查询 - 一个带有函数sum和一个带有DISTINCT的嵌套查询
SELECT SUM(Transaction_Amount)
FROM (
SELECT DISTINCT
tt.Transaction_Amount, t.Transaction_ID
FROM
ItemTracker_dbo.Transaction_Type tt
JOIN
ItemTracker_dbo.Transaction t
ON
tt.Transaction_ID = t.Transaction_ID
JOIN
ItemTracker_dbo.Purchase p
ON
p.Transaction_ID = tt.Transaction_ID
JOIN
ItemTracker_dbo.Item i
ON
i.Item_ID = p.Item_ID
WHERE
t.TimeStamp >= $start AND t.TimeStamp <= $end
AND
tt.Transaction_Format IN ('cash', 'credit')
AND
i.Client_ID = $client_ID
) table
我希望我理解你的问题。如果没有,那么抱歉误会
答案 3 :(得分:0)
您可以按Transaction_ID和Transaction_amount对结果进行分组,然后获取全局总和。
select sum(Transaction_amount) from
(select Transaction_ID, Transaction_amount
from [...]
group by Transaction_ID, Transaction_amount) a