473,379 Members | 1,190 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Concat instead of SUM when grouping results

Hello,

I have a very simple problem which I will illustrate with an example:

I have the following records in my table:
A 1 C
A 2 C
A 3 C
B 8 K
B 9 K

I now want to group them and the result has to be:
A 1,2,3 C
B 8,9 K

So the results in the second row have to be concatenated. I guess
there is no function to do this... What is the simplest solution?

Kind regards,

Bart Warnez
Nov 23 '07 #1
11 3732
Hi Bart,

I've seen this question answered very neatly before, so with a bit of
digging and some copy/paste I came up with:

CREATE TABLE test (test1 VARCHAR(5), test2 varchar(5), test3
varchar(5))

INSERT INTO test(test1, test2, test3)
SELECT 'A', '1', 'C'
UNION ALL
SELECT 'A', '2', 'C'
UNION ALL
SELECT 'A', '3', 'C'
UNION ALL
SELECT 'B', '8', 'C'
UNION ALL
SELECT 'B', '9', 'C'

SELECT test1, SUBSTRING((select ', ' + test2 as [text()]
from test t
where t.test1 = ot.test1
for xml path(''), elements), 3, 100) as test2, test3
FROM test ot
GROUP BY test1, test3

DROP TABLE test

which seems to work :)

Good luck!
J
Nov 23 '07 #2
On 23 nov, 12:52, jhofm...@googlemail.com wrote:
Hi Bart,

I've seen this question answered very neatly before, so with a bit of
digging and some copy/paste I came up with:

CREATE TABLE test (test1 VARCHAR(5), test2 varchar(5), test3
varchar(5))

INSERT INTO test(test1, test2, test3)
SELECT 'A', '1', 'C'
UNION ALL
SELECT 'A', '2', 'C'
UNION ALL
SELECT 'A', '3', 'C'
UNION ALL
SELECT 'B', '8', 'C'
UNION ALL
SELECT 'B', '9', 'C'

SELECT test1, SUBSTRING((select ', ' + test2 as [text()]
from test t
where t.test1 = ot.test1
for xml path(''), elements), 3, 100) as test2, test3
FROM test ot
GROUP BY test1, test3

DROP TABLE test

which seems to work :)

Good luck!
J
Hey, thank you very much, it works :). The only problem is that it
lasts more than 10 s to execute it and that with only 5 records :(.

Kind Regards,

Bart
Nov 23 '07 #3
I have also tried out the solution below (with the same test-table),
with a function. But again the response time is very slow...

create function dbo.fn_groupIt(@test1 varchar(5),@test3 varchar(5))
returns varchar(5000)
as
begin
declare @out varchar(5000)
select @out = coalesce(@out + ',' + convert(varchar,test2),
convert(varchar,test2))
from test
where test1 = @test1 and
test3 = @test3

return @out
end

select test1, dbo.fn_groupIt(test1,test3) test2,test3
from (
select test1,test3
from test
group by test1,test3
) a
Nov 23 '07 #4
Hi Bart,

What spec server are you using? I can run either script in under a
second :-/

J
Nov 23 '07 #5
On 23 nov, 15:46, jhofm...@googlemail.com wrote:
Hi Bart,

What spec server are you using? I can run either script in under a
second :-/

J
Ok, I asked for another testserver because the first one was
apparently overloaded (read: dead). I didn't notice that at first
because a simple table-select took no time at all and those other
scripts took 10-20 seconds. On the new server, it takes no time...
Yes, you are right and I am happy :). Thank you very much!

Bart
Nov 23 '07 #6
>I guess there is no function to do this... What is the simplest solution? <<

Do it in the front end instead violating 1NF in the Database side.

Nov 25 '07 #7
On 25 nov, 19:59, --CELKO-- <jcelko...@earthlink.netwrote:
I guess there is no function to do this... What is the simplest solution? <<

Do it in the front end instead violating 1NF in the Database side.
Hi,

I'm not an expert in that area, but I thought NF had to do with
database design and not with querying a database? Correct me if I'm
wrong.

I would like most of the logic on server side, (the report result is
retrieved by an excel report that mainly adds lay-out and adds the
possibility to further process the results) because when an update of
the report is needed, I only need to change the stored procedure and
not the 'front-end' excel reports with everybody that uses it.
Kind regards,

Bart
Nov 26 '07 #8
"Bart op de grote markt" <wa*****@googlemail.comwrote in message
news:3e**********************************@s36g2000 prg.googlegroups.com...
On 25 nov, 19:59, --CELKO-- <jcelko...@earthlink.netwrote:
>I guess there is no function to do this... What is the simplest
solution? <<

Do it in the front end instead violating 1NF in the Database side.

Hi,

I'm not an expert in that area, but I thought NF had to do with
database design and not with querying a database? Correct me if I'm
wrong.
You're "wrong".

You can't really separate the two. That's like saying that wheels on a car
have to do with the design, not with the actual driving.

If you design your database properly, your queries follow from that.

>
I would like most of the logic on server side, (the report result is
retrieved by an excel report that mainly adds lay-out and adds the
possibility to further process the results) because when an update of
the report is needed, I only need to change the stored procedure and
not the 'front-end' excel reports with everybody that uses it.
Then do it in a middle layer. What happens when your DB changes for other
reasons but your reports aren't supposed to?

>
Kind regards,

Bart


--
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html
Nov 26 '07 #9
If you design your database properly, your queries follow from that.

This is nice in theory, but in practice I have seen many occasions
where reporting requirements simply don't align with the database
(which you often have no control over and may have been designed for
an input system for example). Short of designing a new database and
ETL'ing your data across (which there certainly is a market for but in
a lot of cases would be overkill to meet a single requirement),
sometimes you have to write "non-standard" queries.
Then do it in a middle layer. What happens when your DB changes for other
reasons but your reports aren't supposed to?
Why would a stored procedure not qualify as a middle layer? It
provides a convenient interface between the front-end and the database
and still allows the use of this type of query which, in my opinion,
is neat and easy to implement in SQL. Does it matter if your entire
data structure underneath the stored proc changes as long as the proc
continues to serve up the same results?

J
Nov 26 '07 #10
On 26 nov, 14:09, "Greg D. Moore \(Strider\)"
<mooregr_deletet...@greenms.comwrote:
"Bart op de grote markt" <warn...@googlemail.comwrote in messagenews:3e**********************************@s 36g2000prg.googlegroups.com...
On 25 nov, 19:59, --CELKO-- <jcelko...@earthlink.netwrote:
I guess there is no function to do this... What is the simplest
solution? <<
Do it in the front end instead violating 1NF in the Database side.
Hi,
I'm not an expert in that area, but I thought NF had to do with
database design and not with querying a database? Correct me if I'm
wrong.

You're "wrong".

You can't really separate the two. That's like saying that wheels on a car
have to do with the design, not with the actual driving.

If you design your database properly, your queries follow from that.
I have not said that database design has nothing to do with querying a
database... But a query of a database is combining the available data
to hava a certain result. Putting the normal forms into your database
is a way to avoid data loss in your database when you update or delete
your data. If I query a database for a report, then the result won't
interfere with the database itself, it just gives a view on your data.
I don't want to be offensive or so, but I'm not convinced yet.

And ok, I did not design the database... it is a database from a new
application my company bought. (In fact it's about two databases from
two different applications that have to be linked in a report, but I
won't go too far to explain that :-) )
I would like most of the logic on server side, (the report result is
retrieved by an excel report that mainly adds lay-out and adds the
possibility to further process the results) because when an update of
the report is needed, I only need to change the stored procedure and
not the 'front-end' excel reports with everybody that uses it.

Then do it in a middle layer. What happens when your DB changes for other
reasons but your reports aren't supposed to?
As has been said by J above, the Stored Procedure acts as middle layer
between the database and the reports. If there is an update of the
database (e.g. new product version), I will adapt the stored
procedure, so that the user doesn't even notice that anything has
changed.
Kind regards and thx for all your comments

Bart
Nov 26 '07 #11
You're "wrong".

Actually Greg - You're "wrong".

SQL Server is a data engine and not just a relational data storage method.

There are lots and lots of extensions and features in SQL Server to help us
gain more performance, more simplicity instead of having to code stuff in
the middle tier all the time.

For instance, if I was writing a data export why on earth would I want to
use a second programming langauge that adds complexity when I can easily use
the functions and features in T-SQL.

There is a move more to putting business logic in the data engine rather
than just using the data engine as a put and get object - see research by
Jim Gray.
Then do it in a middle layer. What happens when your DB changes for other
reasons but your reports aren't supposed to?
It would be a bigger change if you had done it in the middle tier - both the
data access queries would change AND the middle tier source code. That's a
lot more testing, development - it's higher risk, more complicated etc...

--
Tony Rogerson, SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson
[Ramblings from the field from a SQL consultant]
http://sqlserverfaq.com
[UK SQL User Community]

Nov 26 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Debbie Davis | last post by:
Hi there, SQL 2000 I have the following query: SELECT sponsor, COUNT(sponsor) * 2 AS total FROM Referrals GROUP BY sponsor Works great, returns the sponsor and the total * 2 of their...
4
by: Gerald Aichholzer | last post by:
Hello, I need to specify the following attribute in an xhtml-file containing TAL templates: <div tal:attributes="onMouseOver concat('func(',xyz,')')"> which results in <div...
3
by: ahaque38 | last post by:
Hello. Using A2K SP3, I am having the following problem with a report using "Sorting and Grouping". I have recently added a grouping in the reports for "Category2<>'CONTRACTS'". I have...
8
by: Doug Stiers | last post by:
Is there a downside to using string.concat? Other than a little overhead? str1 = string.concat(str1,str2) vs. str1 &= str2 It seems to me like the string class should be optimized to do this...
1
by: Trint Smith | last post by:
Ok, I have a webform that has these checkboxes: 1. something 2. something else 3. and something else When the user clicks on the checkbox, I want all of the selections to go into a textbox...
13
by: Raman | last post by:
Hi All, Could any one tell me How to concatenate two strings using recursion. And also how to trim a string using recursion.(in C, offcourse) Regards, Raman Chalotra
18
by: NoWhereMan | last post by:
Maybe a stupid question. ------------------------- 1 ------------------------- $str = ''; for($i=0; $i<10; $i++) $str .= $i;
9
by: JakeTheSnake | last post by:
Hello, I'm new here, but am really impressed with the positive attitude! I was wondering if someone could give me some help or point me in the right direction. I have a query that returns the...
8
by: Peter Larsen [CPH] | last post by:
Hi, How do i concat two dictionaries aka the following sample: Dictionary<int, stringa; Dictionary<int, stringb; b.Add(a); What is the easiest way to concat two dictionaries ??
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.