简体   繁体   中英

Aggregate multiple columns based on single group by in sql

I have a table which contains data in attached image format 在此处输入图片说明

Or sample data

transactionDate         |   AllocatedHrs | ActivityName                     
2014-10-10 10:43:55.763,1.5830000000000000,abc
2014-10-10 10:13:55.763,1.2830000000000000,def
2014-10-10 11:33:55.763,0.2830000000000000,ghi
2014-10-10 11:53:55.763,0.7170000000000000,ijk

I need to group the data for this table based on transactionDate , the data of AllocatedHrs should get added and third column should add the names of grouped tables ie

network                        | Sum                    |Date
abcdef2014-10-10 10:43:55.763, 2.8660000000000000, 2014-10-10 10:43:55.763
ghiijk2014-10-10 11:33:55.763,   1.0,              2014-10-10 11:33:55.763

I am using the following query

with A as 
(
  SELECT DATEADD(hour, DATEDIFF(hour, 0, transactionDate), 0) as testDate, 
   activityId , AllocatedHrs ,activity_name
  from test_group 
  group by activityId ,transactionDate,AllocatedHrs,activity_name
  )
  select  cast(a.activity_name as VARCHAR) +  cast(a.testDate as VARCHAR) as network
  ,sum(A.AllocatedHrs)as allc 
  ,a.activityId as activity
  from A
  group by a.testDate
  order by a.activityId

But whenever i am trying to run the same i am getting the following error

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

DECLARE @table1 TABLE
  (
     transactionDate DATETIME,
     AllocatedHrs    NUMERIC(22, 10),
     ActivityName    VARCHAR(200)
  )

INSERT INTO @table1
VALUES      ('2014-10-10 10:00:00.000',1.5830000000000000,'abc'),
            ('2014-10-10 10:00:00.000',1.2830000000000000,'def'),
            ('2014-10-10 11:00:00.000',0.2830000000000000,'ghi'),
            ('2014-10-10 11:00:00.000',0.7170000000000000,'ijk')

SELECT t1.transactionDate,
       Sum(AllocatedHrs),
       (SELECT CONVERT(VARCHAR, ActivityName)
        FROM   @table1 b
        WHERE  b.transactionDate = t1.transactionDate
        ORDER  BY ActivityName
        FOR XML PATH(''))
       + CONVERT(VARCHAR, t1.transactionDate, 111 )
FROM   @table1 t1
GROUP  BY t1.transactionDate 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM