SQL从2个表中添加值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL从2个表中添加值相关的知识,希望对你有一定的参考价值。
我需要从两个表中添加uniqueid和WBid。通过下面的输入,我从两个表中获取了正确的数据,但它只是将它列在行中,而不是对它进行求和。
select distinct COUNT(l.uniqueid), SUM(r.WBid), l.uniqueid, l.firstname, ``l.lastname, l.email, l.phone, l.mobile, l.address, l.city FROM EDW..lookupuser l
INNER JOIN DB..DimBD b on b.userid = l.userId
INNER JOIN DB..FactVP v on v.BidderId = b.bidderid
INNER JOIN DB..FactRD r on r.buyerid = b.bidderid
and r.AuctionDate > '2012-12-31'
GROUP BY l.uniqueid, l.email, l.phone, l.mobile, l.address, l.city, l.firstname, l.lastname
UNION
select distinct COUNT(l.uniqueid), SUM(t.WBid), l.uniqueid, l.firstname, l.lastname, l.email, l.phone, l.mobile, l.address, l.city FROM EDW..lookupuser l
INNER JOIN DB..DimB b on b.userid = l.userId
INNER JOIN DB..FactVP v on v.BidderId = b.bidderid
INNER JOIN DB..FactTA t on t.BidderId = b.bidderid
and t.AuctionDate > '2012-12-31'
GROUP BY l.uniqueid, l.email, l.phone, l.mobile, l.address, l.city, l.firstname, l.lastname
order by l.email asc
答案
你必须先做工会,然后把它弄清楚。否则你会得到两组结果:
SELECT DISTINCT COUNT(uniqueid), SUM(WBid), uniqueid, firstname, lastname, email, phone, mobile, address, city
FROM (
SELECT l.uniqueid, r.WBid, l.uniqueid, l.firstname, ``l.lastname, l.email, l.phone, l.mobile, l.address, l.city
FROM EDW..lookupuser l
INNER JOIN DB..DimBD b ON b.userid = l.userId
INNER JOIN DB..FactVP v ON v.BidderId = b.bidderid
INNER JOIN DB..FactRD r ON r.buyerid = b.bidderid AND r.AuctionDate > '2012-12-31'
UNION
SELECT l.uniqueid, t.WBid, l.uniqueid, l.firstname, l.lastname, l.email, l.phone, l.mobile, l.address, l.city
FROM EDW..lookupuser l
INNER JOIN DB..DimB b ON b.userid = l.userId
INNER JOIN DB..FactVP v ON v.BidderId = b.bidderid
INNER JOIN DB..FactTA t ON t.BidderId = b.bidderid AND t.AuctionDate > '2012-12-31'
) x
GROUP BY uniqueid, email, phone, mobile, address, city, firstname, lastname
ORDER BY email ASC
以上是关于SQL从2个表中添加值的主要内容,如果未能解决你的问题,请参考以下文章