SQL multiple rows with same row names to column - sql

I have the following data in SQL (nvarchar, nvarchar)
Name: Test Person
Phone Number: 290831283
Fax Number: 192389182
Email Address: test#test.com
Name: Abacus Testing
Phone Number: 901823908
Fax Number: 9213989182
Email Address: abacus#test.com
How can I format this data to be:
[Name] [Phone Number] [Fax Number] [Email Address]
Test Person 290831283 192389182 test#test.com
Abacus Testing 901823908 9213989182 abacus#test.com
So basically setting the rows into matching column
I was hoping to use a Pivot table, but I only get the first row due to aggregation.
SELECT [Name], [Phone Number], [Fax Number], [Email Address]
FROM
(
SELECT
ColumnName,
Data
FROM
TheData
) SRC
PIVOT
(
MAX(Data)
FOR ColumnName IN ([Name], [Phone Number], [Fax Number], [Email Address])
) PIV
I would prefer no CURSOR methods, any alternatives?
Edit: added other fields available for use
The other fields available are Label Id for each entry. i.e Name=1, PhoneNumber=2, FaxNumber=3, EmailAddress=4
The common Id for each of the 4 entries is also available. i.e first 4 entries have id 1001, second 4 entries have id 1002

Following clarification in the comments you just need to add CommonId in to your source.
This is not an aggregated or spreading column so it will be used as a grouping column and you will get a row per distinct value of that.
SELECT [Name], [Phone Number], [Fax Number], [Email Address]
FROM
(
SELECT
CommonId,
ColumnName,
Data
FROM
TheData
) SRC
PIVOT
(
MAX(Data)
FOR ColumnName IN ([Name], [Phone Number], [Fax Number], [Email Address])
) PIV

Related

Combining two SQL queries in Access

I've been trying for a couple of hours or so this morning to combine two access (Access 365) queries into one statement so I can run a report off of it. I've read around the forums and have tried various combinations but cannot get them to work. I'm not an SQL guru and was wondering if someone can help and point out where I'm going wrong.
I have a table (data) it has 2 relevant columns
Audit username, Attendance Ref Name,
each time an order is created it gets logged,
if it was electronic the user name is "DRIP" if manually entered it gets the logged in user name.
What I would like is one row for each requester with Column one being the requester name (Attendance Ref Name), Column 2 being number of times the requester appears (Total Number of requests), Column 3 total number of times the requester has made it electronically (Total Number of Electronic requests)
so I can produce a 4th column so show me percentages of electronic requests by the requester
What I have working is two queries
WORKING STATMENTS (written in Notepad - I'm omitting the -- line in access):
--Total number of unique requests per requester
SELECT DISTINCT Data.[Attendance Ref Name], Count(Data.[Attendance Ref Name]) AS [Total Number of requests]
FROM Data
GROUP BY Data.[Attendance Ref Name]
and
--Total Number of unique requester received electronically per Requester.
SELECT DISTINCT Data.[Attendance Ref Name], Count(Data.[Attendance Ref Name]) AS [Total Number of Electronic requests]FROM Data WHERE (((Data.[Audit Username])="DRIP"))
GROUP BY Data.[Attendance Ref Name];
WHAT I have tried:
SELECT DISTINCT Data.[Attendance Ref Doctor Name], Count(Data.[Attendance Ref Doctor Name]) AS [Total Number of requests]FROM Data
UNION
SELECT DISTINCT Data.[Attendance Ref Doctor Name], Count(Data.[Attendance Ref Doctor Name]) AS [Total Number of Electronic requests]FROM Data WHERE (((Data.[Audit Username])="DRIP"))
GROUP BY Data.[Attendance Ref Doctor Name];
and
SELECT
(SELECT DISTINCT Data.[Attendance Ref Doctor Name], Count(Data.[Attendance Ref Doctor Name])FROM Data) AS [Total Number of requests],
(SELECT DISTINCT Data.[Attendance Ref Doctor Name], Count(Data.[Attendance Ref Doctor Name])FROM Data WHERE Data.[Audit Username]="DRIP")AS [Total Number of Electronic requests]
I have even been through https://www.w3schools.com/sql/default.asp tutorials
but I cannot get them working anyone able to help please and put me out of my misery?
thanks in advance for any help
You need to use a join to link the result from your first and second query together.
Assuming all ref names are in both tables, you can use the following:
SELECT q1.[Attendance Ref Name], q1.[Total Number of requests], q2.[Total Number of Electronic requests]
FROM (
SELECT DISTINCT Data.[Attendance Ref Name], Count(Data.[Attendance Ref Name]) AS [Total Number of requests]
FROM Data
GROUP BY Data.[Attendance Ref Name]
) AS q1
INNER JOIN (
SELECT DISTINCT Data.[Attendance Ref Name], Count(Data.[Attendance Ref Name]) AS [Total Number of Electronic requests]FROM Data WHERE (((Data.[Audit Username])="DRIP"))
GROUP BY Data.[Attendance Ref Name]
) AS q2
ON q1.[Attendance Ref Name] = q2.[Attendance Ref Name]

Putting two SQL statements together

I am new at SQL and I am just trying to add two SQL statements together which are below. The first table is a basic make table pulling in only fields I need and then the second table is pulling the same information but appending it to the first table I made in Step 1 . I have been doing some research and what I think I need to do is a union query but I am not sure how to go about that any help please?
/*first step*/
/*Select
[NPI],
[Last Name],
[First Name],
[Middle Name],
Suffix,
Gender,
[Spoken Languages]
Into [Provider Table]
From sylvia.dbo.UNIQUEACN*/
/*Second step appending PCCN Providers*/
Insert into [sylvia].dbo.[provider Table] ( NPI, [Last Name], [First Name], [Middle Name], Suffix, Gender, [spoken languages] )
Select sylvia.dbo.[PCCNProviders].NPI, sylvia.dbo.PCCNProviders.[Last Name],sylvia.dbo.PCCNProviders.[First Name], sylvia.dbo.PCCNProviders.[Middle Name], sylvia.dbo.PCCNProviders.suffix, sylvia.dbo.PCCNProviders.gender, sylvia.dbo.PCCNProviders.[Spoken Languages]
From sylvia.dbo.[PCCNproviders];
Because your 2 tables have the same number and order of columns, you can simply execute the below query. Use UNION ALL if you want to keep duplicated values from both tables or just UNION if you want all duplicated values to be removed.
SELECT *
-- INTO [Combined_table]
FROM sylvia.dbo.UNIQUEACN
UNION ALL
SELECT *
FROM sylvia.dbo.[PCCNproviders]
Thank you I did just that I did a union query and its way cleaner then what I was doing .. Thanks again!! Ive been doing SQL for a week and as you can tell its a struggle but getting there
Select
a.[NPI],
a.[Last Name],
a.[First Name],
a.[Middle Name],
a.Suffix,
a.Gender,
a.[Spoken Languages]
Into [Provider test]
From sylvia.dbo.UNIQUEACN a
Union
Select
b.[NPI],
b.[Last Name],
b.[First Name],
b.[Middle Name],
b.Suffix,
b.Gender,
b.[Spoken Languages]
From sylvia.dbo.[PCCNproviders] b

Have blank fields in query on purpose

I have a Microsoft Access database with the following table:
TableName: Parts
Cabinet ID - Number
Part ID - Number
PartClass - Number
Width - Number (double)
Length - Number (double)
Description - Text
I use the following SQL queries to get three views:
DoorPanels:
SELECT Parts.[Cabinet ID], Count(Parts.[Cabinet ID]) as Qty, Parts.Description as Name Parts.Width, Parts.Length
FROM Parts
WHERE PartClass=13 GROUP BY Parts.[Cabinet ID], Parts.Description, Parts.Width, Parts.Length
ORDER BY Parts.[Cabinet ID]
DoorRails:
SELECT Parts.[Cabinet ID], Count(Parts.[Cabinet ID]) as Qty, Parts.Description as Name Parts.Width, Parts.Length
FROM Parts
WHERE PartClass=14 GROUP BY Parts.[Cabinet ID], Parts.Description, Parts.Width, Parts.Length
ORDER BY Parts.[Cabinet ID]
DoorStiles:
SELECT Parts.[Cabinet ID], Count(Parts.[Cabinet ID]) as Qty, Parts.Description as Name Parts.Width, Parts.Length
FROM Parts
WHERE PartClass=15 GROUP BY Parts.[Cabinet ID], Parts.Description, Parts.Width, Parts.Length
ORDER BY Parts.[Cabinet ID]
This gives me three separate views that hold only the parts that I want. Now, I have an additional table:
TableName: Doors
Cabinet ID - Number
Door ID - Number
Width - Number (double)
Height - Number (double)
I use another query to create a view for this as well:
SELECT Doors.[Cabinet ID], Count(Doors.[Door ID]) as Qty FROM Doors GROUP BY Doors.[Cabinet ID] ORDER BY Doors.[Cabinet ID]
So, finally I want to join all of these together...but this is where I am at a bit of a loss. What I need to get, would be a result like this, from the data that I have retrieved:
Doors.[Cabinet ID] Doors.Qty DoorRails.* DoorStiles.* DoorPanels*
1 2 [data] [data] [data]
[data] [data] [data]
2 3 [data] [data] [data]
[data] [data] [data]
[data] [data] [data]
Now, to decipher what I am talking about in the result above, you can see that for [Cabinet ID] 1, I have a door quantity of 2, so I need 2 records for the parts for that door. [Cabinet ID] 2 has 3 doors, so I need 3 records for all the door parts for that.
Now, I understand that this is a little complicated, and possibly...well...impossible, but I have been working on this for a few days and haven't come up with anything. If it's not possible, I would appreciate the experts here telling me so.
Just for FYI - I can't make ANY changes to the database or the structure, all that I can do is run Queries against it.
I think the easiest way to do this would be via a Cartesian join to a table that simply has rows with a single field incrementing from 1 to the maximum number of doors you will ever need. For example,
Counter.Num
-----------
1
2
3
If you cannot even create local tables for your own use, you could simulate the above using a UNION query. Access has some limitations here, so you'll need to reference an existing table even though you won't use any of its rows. For example,
SELECT TOP 1 1 AS Num FROM msysobjects
UNION ALL
SELECT TOP 1 2 AS Num FROM msysobjects
UNION ALL
SELECT TOP 1 3 AS Num FROM msysobjects
Then use this Counter table/query as follows:
SELECT D.[Cabinet ID], C.Num & " of " & Count(D.[Door ID]) AS [Door Number],
DR.*, DS.*, DP.*
FROM Counter AS C,
((Doors AS D INNER JOIN DoorRails AS DR ON D.CabinetID=DR.CabinetID)
INNER JOIN DoorStiles AS DS ON D.CabinetID=DS.CabinetID)
INNER JOIN DoorPanels AS DP ON D.CabinetID=DP.CabinetID
WHERE C.Num <= Count(D.[Door ID])
GROUP BY D.[Cabinet ID]
ORDER BY D.[Cabinet ID], C.Num
This will be a slightly different result than your sample. The difference is the Cabinet ID will be repeated for each door. Since the quantity would also be repeated, I substituted the door number instead (in the form of "1 of 2", "2 of 2", etc.).

vb.net select statement with parameters

Hi all I am having a weird problem on a aspx page.
I have a select statement where the where clause has 2 options
The result of the query should populate a datagrid
SELECT TOP 10
[Last Name], [First Name], SSN,
[Box Label], [Original Box Number],
[Student ID], FolderName, DOB, [Transcript On File Y/N],
UserID, [School ID],
[Box Number], [School Name], Comment, SW, Code, Descrip
FROM
Main
WHERE
([Last Name] = ?) OR ([First Name] = ?)
When I put just one of the parameters (ie: lastname) nothing gets populated to the datagrid, but if I put data in both parameter is fills the datagrid with data.
I tested the select statement to verify that it does get data when I choose one or the other, but when I run it online it requires both fields to have data.
very weird...

Entire Union query returns no results if part of it returns no results

I've created the folllowing Union query, which works fine most of the time:
SELECT [%$###_Alias].[Contact ID], [%$###_Alias].[Mailing Name]
FROM (SELECT [Referrals - Contacts Within Organisations].[Contact ID], [Referrals - Contacts Within Organisations].[Mailing Name], [Referrals - Contacts Within Organisations].[Surname], [Referrals - Contacts Within Organisations].[First name]
FROM [Referrals - Contacts Within Organisations]
UNION SELECT "0" as [Contact ID], "View all contacts" as [Mailing Name], "0" as [Surname], "0" as [First name]
FROM [Referrals - Contacts Within Organisations]) AS [%$###_Alias]
ORDER BY [%$###_Alias].Surname, [%$###_Alias].[First name];
This adds an initial row of "View all contacts" at the top of whatever the query returns.
However, if the "actual" query part of it returns no results, the entire query returns no results, whereas I'd always want the initial row to appear regardless.
Is this possible, and if so, what am I doing wrong? Thanks.
EDIT: Thanks all for your help. The final working query is below for reference of anyone else who needs this sort of thing:
SELECT A.[Contact ID], A.[Mailing Name]
FROM (SELECT "0" as [Contact ID], "View all contacts" as [Mailing Name], "0" as [Surname], "0" as [First name]
FROM [Dummy]
UNION
SELECT [Referrals - Contacts Within Organisations].[Contact ID], [Referrals - Contacts Within Organisations].[Mailing Name], [Referrals - Contacts Within Organisations].[Surname], [Referrals - Contacts Within Organisations].[First name]
FROM [Referrals - Contacts Within Organisations]) AS A
ORDER BY A.Surname, A.[First name];
To return always one row with data in SQL, even when you are manually providing the values, you need to be selecting from a table that has at least one row, I suggest using a tblDummy with one field of random information.
e.g:
SELECT "Hello", "Goodbye"
FROM tblDummy
As a side note I would also try and get rid of:
[%$###_Alias]
This can be accomplished by aliasing your Derived tables by adding:
(SELECT * FROM Blah) AS A
for example to name the derived table as A