基于Join - SQL Server 2012合并两个表

时间:2015-12-07 13:44:41

标签: sql-server

我的第一张桌子

select * 
from dbo.tblusertasks

   id   pagename              search    _update     _delete   _insert
    1   CustomerMaster          0          0           0         0
    2   OrganizationMaseter     0          0           0         0
    3   Vendor/SupplierMaster   0          0           0         0

我的第二张表

select * 
from dbo.tblpages

id  pagenameid  userid  createdby   search  _update _delete _insert
1   1             1        1          1        1       1       1
2   2             1        1          1        1       1       1

我想合并这两个,需要结果为

id  pagename               search   _update _delete _insert
1   CustomerMaster           1         1       1      1
2   OrganizationMaseter      1         1       1      1
3   Vendor/SupplierMaster    0         0       0      0

我已尝试过此查询,但无效

SELECT  
    pg.id, pg.[pagename], tblp.[search],tblp.[_update] , 
    tblp.[_delete], tblp.[_insert] 
FROM 
    tblpages pg 
LEFT JOIN 
    [tblusertasks] tblp ON tblp.pagename = pg.id 
WHERE
    tblp.userid = 1

它正在返回(我尝试了左右连接,但它仍然返回相同):

id  pagename            search  _update _delete _insert
1   CustomerMaster         1       1       1      1
2   OrganizationMaseter    1       1       1      1

2 个答案:

答案 0 :(得分:0)

SIcne你说你已经尝试了LEFT和RIGHT JOIN并且没有工作改变表格arounf无济于事。你需要这样做:

SELECT pg.id,
       pg.[pagename],
       tblp.[search],
       tblp.[_update],
       tblp.[_delete],
       tblp.[_insert]
FROM [tblusertask] tblp
     LEFT JOIN tblpages pg
        ON tblp.ID = pg.pagenameid

这应该有用。

答案 1 :(得分:0)

希望这会有所帮助...... 这使您可以灵活地按PageName ... count,sum等进行分区。

SELECT pagename,
    T.pagenameid,
    ISNULL(T.search, 0) AS search,
    ISNULL(T._update, 0) AS _update,
    ISNULL(T._delete, 0) AS _delete,
    ISNULL(T._insert,0) AS _insert
FROM
(
SELECT 
    MAX(U.ID) OVER (PARTITION BY pagename) AS pagenameid,
    MAX(U.search) OVER (PARTITION BY pagename) AS search,
    MAX(U._update)  OVER (PARTITION BY pagename) AS _update,
    MAX(U._delete)  OVER (PARTITION BY pagename) AS _delete,
    MAX(U._insert)  OVER (PARTITION BY pagename) AS _insert
FROM 
    tblusertasks U
LEFT JOIN   
    tblpages P ON U.id=P.pagenameid
)T
INNER JOIN tblusertasks UT ON UT.id=T.pagenameid

RESULT

enter image description here