列出具有重复值的记录

时间:2014-04-18 03:04:33

标签: sql sql-server

我在sql server 2008上有以下表格:

projectdetailId|projectId|recordTypeID|value|auditDate
1|100|1|abc|10-01-2014|
2|100|1|abc|10-01-2014|
3|100|1|def|10-01-2014|
4|200|1|mno|23-01-2014
...
...

对于大于01-01-2014的记录,我需要使用重复值以及值本身提取projectID。 所以,在上面的例子中:

100,IDs=abc

我执行以下操作:

select
     projectId,
     IDs = STUFF(
    (SELECT ','+ CAST(g2.[value] AS VARCHAR(255)) 
      FROM ProjectDetail g2
      WHERE g2.recordType=1
            and g1.value=g2.value
            and g1.recordType=g2.recordType
            and g1.projectId=g2.projectIdand
            and g2.auditDate > '01-01-2014'
      For XML PATH('')
      ),1,1,'')
FROM ProjectDetail g1
GROUP BY projectId
having COUNT(*) > 1

我收到以下错误:

Column 'value' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Column 'recordType' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

如何解决此问题?

2 个答案:

答案 0 :(得分:0)

试试这个......

SELECT DISTINCT projectId, 
SUBSTRING((SELECT ', ' + value 
FROM dbo.#temp g2 
WHERE g2.recordTypeID=10 
and g1.value=g2.value 
and g2.projectId = g1.projectId 
and g2.auditDate > '01-01-2014' FOR XML PATH('')), 3, 8000) 
FROM dbo.ProjectDetail g1 WHERE projectId IN 
(SELECT projectId FROM ProjectDetail a GROUP BY projectId HAVING COUNT(projectId) > 1)

答案 1 :(得分:0)

如果你有表Projects,那么你可以按如下方式更正你的查询:

select
     projectId,
     IDs = STUFF(
    (SELECT ','+ CAST(g2.[value] AS VARCHAR(255)) as 'data()' 
      FROM ProjectDetail g2
      WHERE g2.recordType=1
            and g1.value=g2.value
            and g1.recordType=g2.recordType
            and g1.projectId=g2.projectIdand
            and g2.auditDate > '01-01-2014'
      For XML PATH('')
      ),1,1,'')
FROM Projects P
WHERE EXISTS (select projectID
              from ProjectDetail PD ON P.projectID=PD.ProjectID
              having count(*)>1)

OR没有表Projects

   select
         projectId,
         IDs = STUFF(
        (SELECT ','+ CAST(g2.[value] AS VARCHAR(255)) as 'data()' 
          FROM ProjectDetail g2
          WHERE g2.recordType=1
                and g1.value=g2.value
                and g1.recordType=g2.recordType
                and g1.projectId=g2.projectIdand
                and g2.auditDate > '01-01-2014'
          For XML PATH('')
          ),1,1,'')
    FROM  (select projectID
           from ProjectDetail PD
           having count(*)>1) P