GROUP BY to combine/concat a column
Hi,
SELECT tblFuelCostDetails.TripId, tblFuelCostDetails.PurchaseDate,
tblPetrolPumps.PumpName+CONVERT(nvarchar(50), tblFuelCostDetails.Quantity) as Pump
FROM tblPetrolPumps INNER JOIN
tblFuelCostDetails ON tblPetrolPumps.PumpId = tblFuelCostDetails.PumpId
Above query output is
TripId PurchaseDate Pump
74 2014-01-16 N.R120.00
73 2014-01-15 N.R10.00
73 2014-01-15 Masranga12.00
I would like to my output like
TripId PurchaseDate Pump
74 2014-01-16 N.R120.00
73 2014-01-15 N.R10.00,Masranga12.00
I find some example from internet where they give solution on a single table, but i could not make it when tables join together.
You can achieve this using a STUFF keyword in SQL. Please see below.
DECLARE @PetrolPumps TABLE
TripID INT,
PurchaseDate Date,
Pump VARCHAR(20)
INSERT INTO @PetrolPumps VALUES(73, '2014/01/15', 'N.R10.00')
INSERT INTO @PetrolPumps VALUES(73, '2014/01/15', 'Masranga12.00')
INSERT INTO @PetrolPumps VALUES(74, '2014/01/16', 'N.R120.00')
SELECT DISTINCT TripID, PurchaseDate,
STUFF((SELECT ', '+Pump FROM @PetrolPumps P2 WHERE P1.TripID = P2.TripID AND P1.PurchaseDate = P2.PurchaseDate
FOR XML PATH('')),1,1,'') AS Pump
FROM @PetrolPumps P1
You can use the same logic on any number of tables. It would have been much easier if you have posted the DDL and some sample DML.
To use the same query use a CTE on the top of this query that has your regualr query. That will suffice your requirement.
;WITH CTE AS
SELECT tblFuelCostDetails.TripId, tblFuelCostDetails.PurchaseDate,
tblPetrolPumps.PumpName+CONVERT(nvarchar(50), tblFuelCostDetails.Quantity) as Pump
FROM tblPetrolPumps INNER JOIN
tblFuelCostDetails ON tblPetrolPumps.PumpId = tblFuelCostDetails.PumpId
SELECT DISTINCT TripID, PurchaseDate,
STUFF((SELECT ', '+Pump FROM CTE P2 WHERE P1.TripID = P2.TripID AND P1.PurchaseDate = P2.PurchaseDate
FOR XML PATH('')),1,1,'') AS Pump
FROM CTE P1
Good Luck :). Visit
http://sqlsaga.com/sql-server/how-to-concatenate-rows-into-one-row-using-stuff/ for a detailed article on STUFF keyword.
Similar Messages
-
Group by on more than 2 columns in SharePoint List
Hi,
Is there any way to use Group-by on more than 2 columns? I know there is a way using SPD which I have implemented as well, however it makes the page READ-ONLY.
Any other way? May be using custom code?Try this
http://chanakyajayabalan.wordpress.com/2010/03/15/group-by-for-more-than-two-columns-in-sharepoint-list/
http://social.msdn.microsoft.com/Forums/sharepoint/en-US/05fbde73-efdb-40dc-a206-55d56caa21d4/make-group-by-for-3-or-more-then-3-columns-in-sharepoint-2010-list?forum=sharepointdevelopmentprevious
http://techtrainingnotes.blogspot.in/2011/01/sharepoint-group-by-on-more-than-2.html -
How to order / group a report by a placeholder column ?
How to order / group a report by a placeholder column populated by the group filter ?
In more detail .....
My Data model editor's select statement brings back (say 1000 rows) from the database.
The group filter decides (on performing certain validations) whether to print a row or not in the report.
Additionally the group filter calculates a "rule type" (just a rule number to say on basis of what rule, the row was selected)
I would like to order/group the report on the placeholder column which was calculated by the group filter ?
Obviously, I won't be able to add the "ORDER BY :CP_RULE_NUMBER" in the sql statement as the placeholer column cp_rule_number
is determined by the group filter level only. (If I do, I get a frequency error)
Any ideas ?
Thanks in advance.
Edited by: user553361 on 8/10/2008 17:35how is the group filter implemented?
If its pure PL/SQL, what about putting the filter-procedure in a stored function into the database? Then you could use the group filter in your query. -
How to create SharePoint: Group By on more than 2 columns in a view (SP 2013)
Hi All,
I want to create Group by column on more than 2 columns in a view in SharePoint 213 list.
The group It for CurrentUser,Yearly,Monthly andWeekly.
How can I achieve It?
Thanks in AdvanceHi,
According to your post, my understanding is that you want to group by on more than 2 columns in a view.
You can use Data View Web Part in SharePoint Designer and add some changes & additions.
For more information, you can refer to:
Group by for more than two columns in SharePoint list
SharePoint: Group By on more than 2 columns in a view (SP 2010)
SharePoint 2013 – Add DataView WebPart with SharePoint Designer 2013
Hack: Data View Web Parts in SharePoint 2013
Best Regards,
Linda Li
Linda Li
TechNet Community Support -
Merge/Concat Multiple Columns in a Flat-File wthin ODI
Hi,
I was wondering if there is a quick way to merge/concat multiple columns in a Flat-File from within ODI, a functionality kinda similar to Essbase load rule files for join/split columns etc.
Please let me know.
ThanksLooks like the CONCAT function works only with Memory Engine. Could someone please confirm this? If this is true, I guess applying the patch is the only resolution.
Thanks -
Concate 3 column data in to one column.
I would like to concate 3 columns in to one column. all three column has datatype as LONG. Is any one knows how to concate long datatype column into one column?
Thanks in Advance812294 wrote:
Is there any way to not use CLOB datatype? I am fetching data from three different tables.And what fetching from three different tables has to do with CLOB?
SQL> set serveroutput on
SQL> declare
2 concat_result clob;
3 tmp long;
4 begin
5 select text
6 into tmp
7 from dba_views
8 where rownum = 1;
9 concat_result := tmp;
10 select data_default
11 into tmp
12 from dba_tab_columns
13 where data_default is not null
14 and rownum = 1;
15 concat_result := concat_result || tmp;
16 select search_condition
17 into tmp
18 from dba_constraints
19 where search_condition is not null
20 and rownum = 1;
21 concat_result := concat_result || tmp;
22 dbms_output.put_line(concat_result);
23 end;
24 /
select
"LIB_IDX","LIB_NAME","VENDOR_NAME","PROTOCOL_NUM","VERSION_NUM","PATH_NAME","MAP
_FILE","FILE_CFGID","MAP_ELEM","ELEM_CFGID","MAP_SYNC" from v$map_library0 OBJ#
IS NOT NULL
PL/SQL procedure successfully completed.
SQL> SY. -
How do you combine a stacked column chart with a clustered column chart
Hello,
I am trying to combine a stacked column chart with a clustered column chart. I know that in Excel there is a way to trick that described on the next site: http://people.stfx.ca/bliengme/ExcelTips/Columns.htm
Is that possible with BI Publisher?
Thank you very much!
Codruta CrisanFinally I get it myself:
You need to use graph type as BAR_VERT_STACK2Y and the declare the series that you want to see on the first Y vertical bar as assignedToY2="false" and the ones that you wanr to see on the second Y vertical bar as assignedToY2="true".
In my case I use 4 Series, 2 stack on the first clustured column and 2 stacked on the second (2Y) clustured colum....see below
graphType="BAR_VERT_STACK2Y">
<SeriesItems>
<Series id="0" assignedToY2="false" color="#BBD6E7"/>
<Series id="1" assignedToY2="false"/>
<Series id="2" assignedToY2="true" color="#004A96"/>
<Series id="3" assignedToY2="true"/>
</SeriesItems> -
How to combine a one columns into 1?
I am using Oracle 8i,
I want to know that how to combine a one columns into 1 row:
For example:
ITEM_NO NAME
01 ABC
01 CDE
Result Set:
ITEM_NO NAME
01 ABC; CDE
I have try to use "SYS_CONNECT_BY_PATH" this function, however, that function can use in Oracle 9i or 10g, NOT 8i.
So please please help me to solve that. Many thanks.Check this thread
Re: column values separated by , -
Fast ESP Combining two navigator columns in index profile
Can we union or combine two Navigators columns result in one column using index profile or FQL?
For example:I have 2 navigators ,KBReleasesNav (refers field KBReleases) and DOCrealeasesNav( refers DOCreleases).there are some common releases in both.I want to show these as one navigator and count as sum of both in UI.I don't think is possible out of the box. May be some kind of customization can do it.
-
Group by and concat one column
Hello, i have a query that gives me the following results (example):
Column1 Column2
Madrid Product1
Madrid Product2
Madrid Product3
And my problem is that i want to have just one record with a group by for column1 and a concatenation of column2 like the following:
Column1 Column2
Madrid Product1/Product2/Product3
How can i do this?
Thanks.select column1, decode(acc, null, null, acc ||' , '|| ac) new_ac
from
( select column1,
column2 ac,
lead(column2) over(partition by column2 order by column1) acc
from table_name
-
Find duplicate values in a table based on combination of two columns.
In table which have millions of records -
I have a Table B under Schema A and i have to find the duplicate records in a table. My Table B uses the combination of columns to identify the unique values.
Scenario is something like this-
One SV_Id can have multiple SV_Details_Id and i have to find out if there is any duplicate in the table. (I have to use combination of columns to identify the unique values and there is no Primary Key, Foreign Key or Unique Key on the table)
then wrote the following query -
select SV_Id,SV_Details_Id count (*) from SchemaA.TableB group by SV_Id,SV_Details_Id having Count (*) > 1 ;
Is it correct as after firing the above query it is returning the rows which is not matching to the duplicate.
kindly help me.
Looking forward for some guidance -
Thanks in advance.What is the desired output??
Do you want to see only unique records??
Or you want to see the duplicate records.
Giving an example will make it easier to provide the required querty.
BTW here is an simple query which is used to delete the duplicate records and keep the unique records in table.
DELETE
FROM table_name a
WHERE EXISTS (SELECT 1
FROM table_name b
WHERE a.sv_id = b.sv_id
AND a.sv_detail_id = b.sv_detail_id
AND a.ROWID > b.ROWID
);Regards
Arun -
All possible combinations of a column as applied to a unique entry?
i am having trouble getting a loop to do what i want, if you
can help me find out what i am doing wrong i would appreciate it:
i have a database with 3 tables in it
table 1 has a list of documents - each one having a primary
key
table 2 has a list of document properties, i will call them
property A, B, and C - each one having a primary key
table 3 is a "relational" table that has a column for a
document's PK and a property's PK that that document has
Example of table 3:
docPK / propPK
1 (Document 1) / 1 (A)
2 (Document 2) / 1 (B)
3 (Document 3) / 2 (B)
1 (Document 1) / 2 (B)
1 (Document 1) / 3 (C)
i need to create a loop in ColdFusion that spits out the
number of possible combinations that exist for each document
so the correct output should look like:
Property A
Document 1
Property B
Document 1
Document 2
Document 3
Property C
Document 3
Property A, Property B
Document 1
Proberty A, Property B, Property C
Document 1
this output displays all possible combinations of properties
under the conditions of existing documents
here is the loop i have so far that does not seem to be
working for me,
<cfoutput query="rsProperties">
<ul>
<cfloop from="0" to="# of properties per document"
index="i">
<li>
<cfoutput group="propPK">
<cfif i EQ "# of properties per document">
[#Trim(propertyName)#]
</cfif>
</cfoutput>
</li>
<ul>
<cfoutput group="docPK">
<li><a href="">#Document
Name#</a></li>
</cfoutput>
</ul>
</cfloop>
</ul>
</cfoutput>
my loop returns possible combinations, but it is not
returning ALL possible combinations, for example it may only return
Property A as a single instead of also returning singles Property B
and C
my query simply consists of a SELECT * FROM [the database]
WHERE [the three tables are set equal (as a join)] AND WHERE
[documents exist]
i know this is all rather confusing but if you can help me
make sense of it i will be grateful
thanks for your timeRead the cfoutput section of the cfml reference manual. If
you don't have one, the internet does.
Look for the example that shows you how to use the group
attribute. -
Combine 2 specific column values into one column
Is there an easy solution to combine column values that is in a group?
In my report I have 1 column group named Activity_Area which has 5 different values Activity 1, Activity2...Activity5.
Let's say I want to merge Activity 4 and Activity 5 and call it ActivityX and gives me the output as below
Activity 1 | Activity 2 | Activity 3 | ActivityXHi Jhonny86,
According to your description, you create a field in database and it contains five values. Then you want to only display four values in report column group, and the last two values should be replaced by “ActivityX”, right?
In your scenario, you can create an table like below:
create table Act(id int,activity varchar(99))
insert into Act select 1,'Activity 1'
insert into Act select 2,'Activity 2'
insert into Act select 3,'Activity 3'
insert into Act select 4,'Activity 4'
insert into Act select 5,'Activity 5'
Then query the table with code like below in query designer, then add the field [Act] into the column group.
If you have any question, please feel free to ask.
Best regards,
Qiuyun Yu
Qiuyun Yu
TechNet Community Support -
Introduction
In SQL Server Reporting Service (SSRS), you may need an average value on column chart.
For the above chart, add an average score line to the chart, you can get which student’s score is larger than average score, and which student’s score is less than average score clearly. This document demonstrates how to add an average line to series groups
on SSRS column chart.
Solution
To achieve this requirement, you can add another values to the chart, change the chart type to line chart. Set the value to average value of the series group and set the line to show only once by using expression. Please refer to the link below to see the
detail steps.
Click the chart to display the Chart Data pane.
Add Score field to the Values area.
Right-click the new inserted Score1 and select Change Chart Type. And then change chart type to line chart in the Select Chart Type window.
Change the Category Group name to Subject. Here are the screenshot for you reference.
Right-click the new inserted Score1 and select Series Properties.
Click the expression button on the right of Value field textbox, type the expression below:
=Avg(Fields!Score.Value,"Subject"))
Click Visibility in the left pane, select “Show or hide based on an expression”, and type in the expression below:
=IIF(Fields!Name.Value="Rancy",FALSE,TRUE)
Name in the expression is one of the Students. Then only one line chart is be displayed by using this expression.
Click Legend in the left pane, type Average_Score to the Custom legend text box.
The report looks like below:
Applies to
Microsoft SQL Server 2005
Microsoft SQL Server 2008
Microsoft SQL Server 2008 R2
Microsoft SQL Server 2012
Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.Thanks,
Is this a supported scenario, or does it use unsupported features?
For example, can we call exec [ReportServer].dbo.AddEvent @EventType='TimedSubscription', @EventData='b64ce7ec-d598-45cd-bbc2-ea202e0c129d'
in a supported way?
Thanks! Josh -
Group by returning more than one column in a single query
Hello,
Sorry to ask such a simple question I guess, but here is my problem.
I'm building a query to get say the smallest user_id from employees in the company by department.
The query goes like :
select emp..department,
min(emp.user_id)
from employee emp
group by emp.department
This gives me the smallest user id by department, which is what I want. But how can I also get the name of that person ?
I know that the "min" condition singles out a unique record (there are no two persons with the same user_id in the department).
But how can I also get the name without turning the above query in a subquery that I would link to the employee table yet again ?
I know the following works but I don't think it's the best option:
select v1.department,
v1.user_id,
emp1.name
from employee emp1,
( select emp..department,
min(emp.user_id)
from employee emp
group by emp.department) v1
where emp1.user_id = v1.user_id
This is just an example of data. It is the principle that I don't quite get.
Any advice would be very much appreciated.
CyrilHi, Cyril,
To find the name of the person who has the lowest user_id
SELECT department
, MIN (user_id) AS lowest_user_id
, MIN (name) KEEP (DENSE_RANK FIRST ORDER BY user_id) AS person_with_lowest_user_id
FROM emp
GROUP BY department;"MIN (name)" above means that if there is a tie for the lowest user_id, then the contender with the first name will be chosen.
If you want to display several columns from the row with the lowest user_id, you have to have a separate "KEEP (DENSE_RANK ...)" expression for each column. In that case, you may find it easier to use the analytic RANK or ROW_NUMBER in a sub-query, like this:
WITH sub_query AS
SELECT department
, user_id
, name
, col2, col3, col4, col5
, RANK () OVER ( PARTITION BY department
ORDER BY user_id
) AS r_num
FROM emp
SELECT * -- or list all columns EXCEPT r_num
FROM sub_query
WHERE r_num = 1;
Maybe you are looking for
-
Need help on adobe forms?explain in details?
hello experts!!! any body explain about Adobe Forms? wat is Adobe form? purpose? it can work on ecc6.0? pls give me example step by step how to create adobe forms? where i wll get ? and wat is diff.between smartforms & adobeforms?
-
Yahoo mail sync issue after upgrade to iOS 5
After i have upgraded to iOS 5 my emails from Yahoo are a month off. Only the emails from a month before are synchronized. As an example, today 10/24 I can see the emails from until 9/13. Any ideas on how to fix this?
-
WHY was the Print icon removed?
WHY was the Print icon removed? I want it back. I used to have an icon for printing on the Toolbar in 3.5.5. When I asked where it went, I found this answer: "That Print window will show every time you go to print something in Firefox 3.6+ versions,
-
Why did AAM install 2 Photoshop Versions?
Two weeks ago, I downloaded and installed Photoshop CC on my Win 7 PRO, PC, desktop with no problems. Today, I attempted to install Photoshop CC on my W 7 Pro laptop which had the desk version of CS6 loaded. I did the following: deactivated CS6; u
-
Restoring my iPhone5 from a backup
I backed up my iPhone5 to iTunes. I got a new phone and tried to restore my new phone... when I started up my new phone it was prompting me for the password to the AppleID of my wife? how do I get my AppleID on my new phone?