Trying to combine multiple rows of result set into single row - sql

select C.customerId,(C.lastName+', '+C.firstName) as CustomerName, C.companyName,
D.companyName+' ('+D.lastName+','+D.firstName+')'
as "Parent CompanyName(Last, First)",S.siteId, S.nickName as siteName,
dbo.GetSiteTelemetryBoxList(s.siteId) as "DeviceId's",
dbo.GetSiteTelemetryBoxSKUList(S.siteId,0) as SKU
from Site S
INNER JOIN Customer C ON S.customerId = C.customerId
INNER JOIN Customer D ON D.customerId = C.parentCustomerId
where S.createDate between DATEADD(DAY, -65, GETUTCDATE()) and GETUTCDATE()
order by C.customerId, S.siteId
The above query returns values that look like this:
CID CustomerName companyName Parent CompanyName(Last, First) SiteName DeviceId SKU
888296 DeYoung, Scott DeYoung Farms Mercier Valley Irrigation (Mercier,Ralph) H E east 200241 NETB12WR
890980 Rust, Marcus NULL Chester Inc. (Young,Scott) Byroad east 346370 NETB12WR
890980 Rust, Marcus NULL Chester Inc. (Young,Scott) Byroad west 345431 NETB12WR
891094 Pirani, Mark A Pirani Farm AMX Irrigation (Burroughs,Michael) hwy 64 south 333721 UNKNOWN
891094 Pirani, Mark A Pirani Farm AMX Irrigation (Burroughs,Michael) HWY 64 North 250162 NETB12WR
891094 Pirani, Mark A Pirani Farm AMX Irrigation (Burroughs,Michael) HWY 64 West 250164 NETB12WR
891094 Pirani, Mark A Pirani Farm AMX Irrigation (Burroughs,Michael) HWY 64 East 250157 NETB12WR
891430 Gammil, Bob Gammil FArms AMX Irrigation (Burroughs,Michael) angel 333677 UNKNOWN
891430 Gammil, Bob Gammil FArms AMX Irrigation (Burroughs,Michael) cemetery 333564 UNKNOWN
The problem I face now is that if a customerId/Name is repeating in the result set. The SiteName, deviceId, SKU should be concatenated to represent the data as one value.
For example, Mark Pirani row would look like
CID CustomerName ... SiteName DeviceId's ...
891904 Pirani, Mark ... hwy 64 south, HWY 64 North, HWY 64 West, HWY 64 East 333721,250162,250164,250157 ...

You can convert the rows with something like this to transform the rows into a concatenated string:
select
distinct
stuff((
select ',' + u.username
from users u
where u.username = username
order by u.username
for xml path('')
),1,1,'') as userlist
from users
group by username

I believe this is more of a SQL query issue than a C# code issue, or more appropriately I believe it more efficient to solve this problem at the query level rather than the code level. Off the top of my head you can use SELECT DISTINCT or GROUP BY clauses.
Here is another StackOverflow question addressing this issue - How do I (or can I) SELECT DISTINCT on multiple columns?

I did some digging and found a few ways to implement it. Basically, the simple solution for this is using mysql's group_concat function. These links discuss how the group_concat can be implemented for SQL server. You can choose one based on your requirements.
Simulating group_concat MySQL function in Microsoft SQL Server 2005? -- This thread discusses a few ways to implement it.
Flatten association table to multi-value column? -- This thread discusses the CLR implemenation of it.
http://groupconcat.codeplex.com/ -- This was just perfect for me. Exactly what I was looking for. The project basically creates four aggregate functions that collectively offer similar functionality to the MySQL GROUP_CONCAT function.

Related

dollar sign, comma, decimal places

I have this code to get total and other fields. what I am interested in
to get total values with $ sign, comma and 02 decimal places, what will be
the best function to use to cover all these.
so the total should reflect like : $ 1,780.00
please advise
select distinct
c.givenname, c.familyname, s.total, p.title,
a.givenname+' '+a.familyname as artist
from
customers as c
join sales as s on c.id=s.customerid
join saleitems as si on s.id=si.saleid
join paintings as p on si.paintingid=p.id
join artists as a on p.artistid=a.id;
result I am getting is like this:
Aloysius Peace 1780.0000 Woman in Black (Femme en noir)Mary Cassatt
Amanda Lynn 1115.0000 Le Moulin de la Galette Pierre-Auguste Renoir
Amanda Lynn 1115.0000 Madamoiselle RiviereJean-Auguste-Dominique Ingres
Amanda Lynn 1115.0000 Pollard Willows With SETting SunVincent Van Gogh
Amelia Rate 2125.0000 Flowers in a Vase with Shells and InseBalthasar Van
Amelia Rate 2125.0000 The Meeting of St Anthony Abbot and St Paul in the
Amelia Rate 2125.0000 The Two Girlfriends Henri de Toulouse-Lautrec
Amelia Rate 2125.0000 Vision After the Sermon, Jacob Wrestling
Use this something like this in your code. (for MS SQL)
select '$' + cast(cast (s.total as decimal (9,2)) as varchar(20)) as price

SQL Oracle - display values only once per column

I'm trying to format a select statement. The assignment specifies that it has to be formatted this way.
I have a database regarding a taxi service. I have to put together a view with the company name, passenger name, and taxi number. Easy. However, the output specifies that the company name should only appear once in the output, at the top of it's own group. So I have:
CREATE VIEW TAXITRIPS(COMPANYNAME, PASSENGERNAME, TAXI#) AS
(SELECT COMPANY.NAME, BOOKING.NAME, VEHICLES.TAXI#
FROM BOOKING JOIN VEHICLES ON BOOKING.TAXI# = VEHICLES.TAXI#
RIGHT OUTER JOIN COMPANY ON VEHICLES.NAME = COMPANY.NAME);
The right outer join is so that companies with no booking recorded are still displayed. If I now run:
SELECT * FROM TAXITRIPS ORDER BY COMPANYNAME ASC;
It will give me something like
COMPANYNAME PASSENGERNAME TAXI#
---------------------------------------------
ABC TAXIS DAVE 192
LEGION CABS
PREMIER CABS SHANE 2154
PREMIER CABS TIM 2169
SILVER SERVICE DAVE 18579
SILVER SERVICE TIM 18124
SILVER SERVICE AARON 18917
No result for legion cabs, all field displayed, et cetera. Assignment specification says it has to look like this.
COMPANYNAME PASSENGERNAME TAXI#
---------------------------------------------
ABC TAXIS DAVE 192
LEGION CABS
PREMIER CABS SHANE 2154
TIM 2169
SILVER SERVICE DAVE 18579
TIM 18124
AARON 18917
The company name should only be displayed on its first row. DISTINCT is not helping. Any advice?
Normally, you would do this at the application layer, because the result set relies on the ordering of the rows -- a bad thing in SQL.
But you can do it as:
SELECT (CASE WHEN ROW_NUMBER() OVER (PARTITION BY c.NAME ORDER BY v.TAXI#) = 1
THEN c.NAME
END) as CompanyName, b.NAME, v.TAXI#
FROM COMPANY c LEFT JOIN
VEHICLES v
ON v.NAME = c.NAME LEFT JOIN
BOOKING b
ON b.TAXI# = v.FLIGHT#
ORDER BY c.name, v.taxi#;
Note: I rearranged the joins to be LEFT JOINs. Most people find that easier to follow than RIGHT JOINs.

Pulling results as rows, easy conversion/translation to columns?

I've been handed a task where I've been asked to make use of an SSIS 2008 package to create a CSV then FTP that CSV, following this tutorial here.
My query isn't quite ready.
I'm pulling results where the columns we're going after are coming out as rows. Been reading around on how to to do this with a cursor + stored procedure, but was wondering if anyone has conquered this obstacle with a simpler solution?
Query
SELECT
b.name as 'field',
a.value
FROM
[PROD_21C_Sitecore_Web].[dbo].[VersionedFields] a
INNER JOIN [PROD_21C_Sitecore_Web].[dbo].[Items] b
on a.FieldId = b.ID
WHERE
ItemId = '8C1D5767-FB1A-47A6-913C-E78AAC24ABC9'
Results
field value
-------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
UnderGradYear 1972
Position1 <p>Cancer Centers of North Carolina, Asheville Hematology Oncology Associates - Medical Oncologist</p>
FellowshipCity1 Winston Salem, NC
FellowshipYear1 1981
__Updated by sitecore\cvance
Position3 <p>St. Joseph's Hospital - Subsection Chief of Hematology/ Oncology</p>
Languages {A5AB043B-86D3-4033-BEDD-928BCA0A13C3}
UnderGradCity Chapel Hill, NC
Interests <p></p>
Locations {6127E1AE-E2BF-4517-8BCB-46590AEB06A8}|{A7D2EA25-1B3F-48AE-B347-FC1E06F48202}
__Revision 22068c83-3504-4d89-a9bf-2a9e83a49ca3
LastName Paschal
FirstName Barton R.
MedicalSchoolCity Atlanta, GA
Fellowship1 <p>Bowman Gray School of Medicine - Medical Oncology</p>
FullName Barton R. paschal
UnderGradSchool University of North Carolina
Residency <p>Louisiana State University Medical Center - Internal Medicine</p>
ResidencyYear 1979
ResidencyCity Shreveport, LA
Specialities {B5B0F45A-E2BE-4F3F-92A6-C39C0D3016C5}|{4FCCE0BC-F3D4-4E27-AA7F-D436E61B2A1B}
AwardsHonors <p>Fellow, American College of Physicians, Phi Beta Kappa</p>
Position1City Asheville, NC
Position2City Asheville, NC
Title MD
__Created 20120509T085416
Internship <p>LSU Medical Center</p>
Photo <image mediaid="{C0F47AFC-CBAE-4043-A52F-BF8E344DC6DA}" mediapath="/Images/Physicians/paschal-web" src="~/media/Images/Physicians/paschal-web.jpg" alt="paschal" height="" width="" hspace="" vspace="" />
Position2 <p>Memorial Mission Hospital - Medical Oncologist & Chair, Department of Internal Medicine</p>
BoardCertifications Board Certified - Internal Medicine, Medical Oncology
Position3City Asheville, NC
__Updated 20130514T080506:635041155069332802
MedicalSchool Emory University School of Medicine - MD
Position4 <p>Hospice of Hendersonville County - Medical Director</p>
Position4City Henderson, NC
MedicalSchoolYear 1976
InternshipCity Shreveport, LA
InternshipYear 1979
ProfessionalAssociations {05E5C7FA-99DC-47C7-AC5E-2DA51D87DD1F}|{E519CAD2-C25F-4ADD-BD91-A4DEF861517B}|{67D7F01D-1695-4963-A149-EDF18354BBCC}
Thank you for looking.
Sounds like you want to PIVOT the data
SELECT
ItemId,
UnderGradYear,
Position1,
FellowshipCity1,
FellowshipYear1
-- add 'columns'
FROM
data -- this 'table' is the result of current query
PIVOT
(
MAX(value)
FOR field IN ([UnderGradYear], [Position1],
[FellowshipCity1], [FellowshipYear1]) -- add 'columns'
) PivotTable
demo
you can then use SSIS to create a CSV of result of above and FTP that file.
Edit: Alternatively you could also use the pivot transformation in SSIS rather than in T-SQL

Joining multiple fields between the same tables

I have a table called 'Resources' that looks like this:
Country City Street Headcount
UK Halifax High Street 20
United Kingdom Oxford High Street 30
Canada Halifax North St 40
Because of the nature of the location fields, I need to map them to a single 'Address' field, and so I also have the following table called 'Addresses':
Country City Street Address
UK Halifax High Street High Street, Halifax, UK
Canada Halifax North St North Street, Halifax, Canada
United Kingdom Oxford High Street High Street, Oxford, UK
(In reality the Address field does add information rather than just combining what is already there.)
I am currently using the following SQL to produce the query:
SELECT Resources.Country, Resources.City, Resources.Street, Addresses.Address,
Resources.Headcount
FROM Resources
INNER JOIN Addresses ON Resources.Country = Addresses.Country
AND Resources.City = Addresses.City
AND Resources.Street = Addresses.Street
This works for me, but I am worried that I have not seen people use this many ANDs in a single join elsewhere, so don't know if it is a bad idea. (This is simplified version - I may need up to 8 ANDs in a single join in another case) Is this the best way to approach the problem, or is there a better solution?
Thanks
Joining on multiple columns is fine. You don't have to "fear" this.
As far as "a better way". I would suggest creating some variable tables, putting some data in them, and posting that TSQL (DDL and DML) here. Then you can get some possible alternatives. Your question is vague at the present (in regards to the "is there a better way" portion of your question)

Customizing FreeTextTable in MS SQL 2000

I'm looking for answers for the following 2 questions (SQL Server 2000). I have an order info table that is indexed so that I may search data on particular columns. So, an example query I might run is:
SELECT top 50 ft_tbl.*, key_tbl.Rank
from OrderInfo as ft_tbl
INNER JOIN FREETEXTTABLE(OrderInfo, Address1, 'W Main St') as key_tbl
ON ft_tbl.OrderInfoID = key_tbl.[KEY]
order by key_tbl.Rank desc
What I'd expect is that SQL would pull everything that matches "W Main St" first since that would have the highest rank, then variations following. However, my results aren't exactly what I'm expecting. Here are the Top 8 results ordered by Rank:
258 W Main St
4322 N Marshall St
221 Main St
320 Broad St
7 S 3rd St
510 Bauerlein St
175 Main Street
108 Maywood St
(I know why this happens now, and am assuming I can fix it with the answer below)
Question: Is there any way to pass in variations where St could be:
St
St.
Street
And W could be
W
W.
West
Thanks in advance! (bump)
Not sure if you have come across an answer for this question, but I think it would be possible to use the Contains clause to take account for these variations. Both of these offer pretty good resources.
http://www.eggheadcafe.com/articles/20010422.asp
http://en.wikipedia.org/wiki/SQL_Server_Full_Text_Search#Inflectional_Searches