选择列表t-sql

时间:2015-03-15 21:29:25

标签: sql sql-server sql-server-2008 tsql sql-server-2008-r2

我有这段代码:

select top 3 
    w.firstName, 
    w.lastName, 
    w.fbId, 
    w.idNumber, 
    w.address, 
    w.phoneNumber, 
    q.userId, 
    c.codeVal,  
    q.bidedItem, 
    SUM(q.bidCount) as sumOfBids, 
    sum(w.codesLeft + q.bidCount) as allCode
from 
    geopl_kubetiAuct.firstWeekBids as q 
join 
    geopl_kubetiAuct.Users w on q.userId = w.Id
join 
    geopl_kubetiAuct.Code c on c.userId = q.userId
where 
    q.bidedItem = 'GalaxyTabs' 
group by 
    w.firstName, w.lastName, w.fbId, w.idNumber, 
    w.address, w.phoneNumber, q.bidedItem, q.userId, c.codeVal
order by 
    sumOfBids desc

它可以正常工作并选择确定所有内容,但存在一个问题。我希望它从geopl_kubetiAuct.Code中选择所有代码。

当我执行join geopl_kubetiAuct.Code c on c.userId = q.userId时,它只检索第一个代码。如何选择代码列表?

1 个答案:

答案 0 :(得分:0)

删除了TOP 3并添加了实际的连接类型

SELECT w.firstName, w.lastName, w.fbId, w.idNumber, w.address, w.phoneNumber, q.userId, c.codeVal,  q.bidedItem, SUM(q.bidCount) AS sumOfBids, sum(w.codesLeft + q.bidCount) AS allCode
FROM geopl_kubetiAuct.firstWeekBids as q 
INNER JOIN geopl_kubetiAuct.Users w on q.userId = w.Id
INNER JOIN geopl_kubetiAuct.Code c on c.userId = q.userId
WHERE q.bidedItem = 'GalaxyTabs' 
GROUP BY w.firstName, w.lastName, w.fbId, w.idNumber, w.address, w.phoneNumber, q.bidedItem, q.userId, c.codeVal
ORDER BY sumOfBids DESC

但是,如果您的数据未在联接的所有表格中填写,请尝试LEFT JOIN

SELECT w.firstName, w.lastName, w.fbId, w.idNumber, w.address, w.phoneNumber, q.userId, c.codeVal,  q.bidedItem, SUM(q.bidCount) AS sumOfBids, sum(w.codesLeft + q.bidCount) AS allCode
FROM geopl_kubetiAuct.firstWeekBids as q 
LEFT JOIN geopl_kubetiAuct.Users w on q.userId = w.Id
LEFT JOIN geopl_kubetiAuct.Code c on c.userId = q.userId
WHERE q.bidedItem = 'GalaxyTabs' 
GROUP BY w.firstName, w.lastName, w.fbId, w.idNumber, w.address, w.phoneNumber, q.bidedItem, q.userId, c.codeVal
ORDER BY sumOfBids DESC