日期:2014-05-18  浏览次数:20496 次

union合并的问题,请大虾指点迷津
SELECT   c.Name   AS   PayMethodName,   b.Name   AS   DepartmentName,   1   AS   COUNT
FROM     crm_Order   a   LEFT   OUTER   JOIN
            crm_Group   b   ON   b.ID   =   a.DepartmentID   LEFT   OUTER   JOIN
            crm_Enumerate   c   ON   c.ID   =   a.PayMethod
WHERE   (a.InsertDate   BETWEEN   '20070101 '   AND   '20070102 ')
         
UNION

SELECT   '无 '   AS   PayMethodName,   crm_Group.Name   AS   DepartmentName,0   AS   COUNT
FROM     dbo.crm_Group
WHERE   crm_Group.ParentID   =   425    

总共查询113条,但是我单独运行第一个条sql就有249条       请问怎么回事?

------解决方案--------------------
SELECT c.Name AS PayMethodName, b.Name AS DepartmentName, 1 AS COUNT
FROM crm_Order a LEFT OUTER JOIN
crm_Group b ON b.ID = a.DepartmentID LEFT OUTER JOIN
crm_Enumerate c ON c.ID = a.PayMethod
WHERE (a.InsertDate BETWEEN '20070101 ' AND '20070102 ')

UNION ALL ------ 加个 all 试试

SELECT '无 ' AS PayMethodName, crm_Group.Name AS DepartmentName,0 AS COUNT
FROM dbo.crm_Group
WHERE crm_Group.ParentID = 425
------解决方案--------------------
SELECT c.Name AS PayMethodName, b.Name AS DepartmentName, 1 AS COUNT
FROM crm_Order a LEFT OUTER JOIN
crm_Group b ON b.ID = a.DepartmentID LEFT OUTER JOIN
crm_Enumerate c ON c.ID = a.PayMethod
WHERE (a.InsertDate BETWEEN '20070101 ' AND '20070102 ')

UNION ALL

SELECT '无 ' AS PayMethodName, crm_Group.Name AS DepartmentName,0 AS COUNT
FROM dbo.crm_Group
WHERE crm_Group.ParentID = 425
------解决方案--------------------
union 会合并 相同的记录,俩个select 都加上distinct 这样再试一下
SELECT distinct c.Name AS PayMethodName, b.Name AS DepartmentName, '1 ' AS [COUNT]
FROM crm_Order a LEFT OUTER JOIN
crm_Group b ON b.ID = a.DepartmentID LEFT OUTER JOIN
crm_Enumerate c ON c.ID = a.PayMethod
WHERE (a.InsertDate BETWEEN '20070101 ' AND '20070102 ')
UNION
SELECT distinct '无 ' AS PayMethodName, crm_Group.Name AS DepartmentName, '0 ' AS [COUNT]
FROM dbo.crm_Group
WHERE crm_Group.ParentID = 425
------解决方案--------------------
都是一样的回答,顶
------解决方案--------------------
单独运行第一个条sql就有249条--- 这个里面的数据一定有重复的

union all 标志表示在并集中保留重复项