How can I display tablenames in resultheader of SQL Server 2008 query - sql

I am analysing a large query with lots of joins on different tables that all get aliases in the joins. Some tables are joined twice with different aliases.
For example the code from this answer:
SELECT *
FROM Blank b
INNER JOIN Ticket t ON b.BlankCode = t.Blank_BlankCode
INNER JOIN MCO_Blank mb ON b.BlankCode = mb.Blank_BlankCode
INNER JOIN Purchase p1 ON t.PurchaseID = p1.PurchaseID
INNER JOIN Purchase p2 ON mb.PurchaseID = p2.PurchaseID
INNER JOIN Payment pa1 ON t.PurchaseID = pa1.PurchaseID
INNER JOIN Payment pa2 ON mc.PurchaseID = pa2.PurchaseID
WHERE pa1.Status = "Paid";
I would like my results grid to display the table aliases in the columns. Is that in any way possible other than using an alias for each column in the select?
So my columnheader should look like this:
b.BlankTypeCode|b.BlankCode|pa1.Amount|pa1.Type|p1.PurchaseDate| pa2.DatePaid
instead of
BlankTypeCode|BlankCode|Amount|Type|PurchaseDate|DatePaid

use This
SELECT b.BlankTypeCode AS [b.BlankTypeCode]
, b.BlankCode AS [b.BlankCode]
, pa1.Amount AS [pa1.Amount]
, pa1.Type AS [pa1.Type]
, p1.PurchaseDate AS [p1.PurchaseDate]
, pa2.DatePaid AS [pa2.DatePaid]
FROM Blank b
INNER JOIN Ticket t
ON b.BlankCode = t.Blank_BlankCode
INNER JOIN MCO_Blank mb
ON b.BlankCode = mb.Blank_BlankCode
INNER JOIN Purchase p1
ON t.PurchaseID = p1.PurchaseID
INNER JOIN Purchase p2
ON mb.PurchaseID = p2.PurchaseID
INNER JOIN Payment pa1
ON t.PurchaseID = pa1.PurchaseID
INNER JOIN Payment pa2
ON mc.PurchaseID = pa2.PurchaseID
WHERE pa1.Status = "Paid";

You will have to alias each column in the select query, but there is a slightly quicker way to do it. Place your mouse cursor before b.BlankCode, and then, holding down the Alt key, click and drag to select down to a few spaces after pa2.DatePaid.
Press Ctrl + C.
Now enter a few spaces after b.BlankCode (to ensure you are past the vertical column of the most stuck out bit, and press Ctrl + V
This is a quick way to create aliases for your columns, and you can type into multiple columns this way as well.

It is not recommended using blank spaces or Dot(.) or any other special charecters is column names
but if you need so then you can change it like this :
change the code like this :
SELECT
b.BlankTypeCode as "b.BlankTypeCode"
, b.BlankCode as "b.BlankCode "
, pa1.Amount as "pa1.Amount"
, pa1.Type as "pa1.Type"
, p1.PurchaseDate as "p1.PurchaseDate"
, pa2.DatePaid as "pa2.DatePaid"
FROM Blank b
INNER JOIN Ticket t
ON b.BlankCode = t.Blank_BlankCode
INNER JOIN MCO_Blank mb
ON b.BlankCode = mb.Blank_BlankCode
INNER JOIN Purchase p1
ON t.PurchaseID = p1.PurchaseID
INNER JOIN Purchase p2
ON mb.PurchaseID = p2.PurchaseID
INNER JOIN Payment pa1
ON t.PurchaseID = pa1.PurchaseID
INNER JOIN Payment pa2
ON mc.PurchaseID = pa2.PurchaseID
WHERE pa1.Status = "Paid";

Related

How to left join tables in LINQ TO SQL to get associated records

I have a linq to sql statement where I am doing join with a bunch of tables , but I need to left join a table as we are not sure if there be any associated records.
We are left joing as we are not sure if every purchase will have a file associated.
Purchase Join - Invc
Purchase Join - FileStore FileStore##Entity
select * from Purchase p
join Invc i on i.Invc_ID = p.Invc_ID
left join FileStore##Entity fe on p.Purchase_ID = fe.Entity_ID
left join FileStore fs on fs.FileStore_ID = fe.FileStore_ID
where p.Purchase_ID = 53
My current linq to sql works for the regular join , how can I left join the file store and store entity table
PurchaseEntity purchase = (from p in TransactionalDbContext.Purchase
join i in TransactionalDbContext.Invc
on p.InvcId equals i.InvcId
where d.Purchase_Id == id
select new DisputeEntity
{
Purchase_Id = p.Purchase_Id,
InvcId = i.InvcId,
SubmittedDate = d.SubmitDt,
InvcNum = i.InvcNum
// get the file elements by left join file
}).FirstOrDefault();
You can easily perform left or right joins by playing with the DefaultIfEmpy method.
Following your example:
from p in dbContext.Purchases
join i in dbContext.Invc on p.InvcId equals i.InvcId
join fe in dbContext.FileStoreEntities.DefaultIfEmpty() on p.Purchase_ID equals fe.Entity_ID
join fs in dbContext.FileStores.DefaultIfEmpty() on fe.FileStore_ID equals fs.FileStore_ID

Problem with the joining of SQL tables via relationships

I am currently having problems trying the run a query for some tables.
Below is what I am trying to do, I just can't seem to get it to work.
I have also duplicated constituent and gifts to show you the relations between soft credit and gifts/constituents
Link to Table Relations Image
SELECT
Constituent.lookup_id,
Constituent.name,
SplitGifts.amount,
SplitGifts.giftaidamount
FROM
dbo.Gifts Gifts
INNER JOIN dbo.Constituent Constituent
ON Constituent.id = Gifts.constituent_id
INNER JOIN dbo.SplitGifts SplitGifts
ON SplitGifts.giftid = Gifts.id
LEFT JOIN dbo.SoftCredit SoftCredit
ON SoftCredit.giftid = Gifts.id
INNER JOIN dbo.Constituent Constituent_1
ON Constituent_1.id = SoftCredit.constituentid
INNER JOIN dbo.Gifts Gifts_1
ON Gifts_1.id = SoftCredit.giftid
INNER JOIN dbo.Package Package
ON Package.id = SplitGifts.packageid
WHERE
Package.lookup_id = N'CORPCHAL'
Basically, I want the
amount and gift_aid_amount from [SplitGifts]
Constituent Name & lookup_id from [constituent] to show up for all Gifts however if a soft credit exists for that gift I need it to get the same fields via the [SoftCredit] table -> Gifts -> SplitGifts -> Fields
You could try if the query below works.
SELECT
Constituent.lookup_id,
Constituent.name,
SplitGifts.amount,
SplitGifts.giftaidamount
FROM
dbo.Gifts Gifts
LEFT JOIN dbo.SoftCredit SoftCredit ON SoftCredit.giftid = Gifts.id
INNER JOIN dbo.Gifts Gifts_1 ON
Gifts_1.id = SoftCredit.giftid OR
(SoftCredit.giftid IS NULL AND Gifts_1.id = Gifts.id)
INNER JOIN dbo.Constituent Constituent ON
Constituent.id = SoftCredit.constituentid OR
(SoftCredit.constituentid IS NULL AND Constituent.id = Gifts_1.constituent_id)
INNER JOIN dbo.SplitGifts SplitGifts ON SplitGifts.giftid = Gifts_1.id
INNER JOIN dbo.Package Package ON Package.id = SplitGifts.packageid
WHERE
Package.lookup_id = N'CORPCHAL'
It joins back to table Gifts (using alias Gifts_1) on the gift reference in SoftCredit or to itself if there is no SoftCredit.
Table Constituent is joined in a similar fashion: it joins on the value of SoftCredit.constituentid and when NULL, it falls back to Gifts_1.constituent_id.
All next joins regarding the gift should refer to Gifts_1 then.
I have not tested it though. But it might give you a hint in a possible solution direction.

how to stop INNER JOIN from showing repeat data

I am working with data on multiple tables and I am trying to get some info but I keep getting repeat data.
SELECT Airport.city, StateInfo.state_name, TravelInfo.destination,
Carrier.unique_carrier_name, CarrierInfo.passengers
FROM Airport
INNER JOIN TravelInfo
ON Airport.airport_id = TravelInfo.destination_airport_id
INNER JOIN Flights
ON Airport.airport_id = Flights.destination_airport_id
INNER JOIN StateInfo
ON Airport.airport_id = StateInfo.airport_id
INNER JOIN Carrier
ON Flights.airline_id = Carrier.airline_id
INNER JOIN CarrierInfo
ON Carrier.airline_id = CarrierInfo.airline_id
WHERE Airport.state = 'CO';
What I am trying to do is get the city name the carrier and a number of passengers but it seems that the output keeps repeating the data.
For example I will get:
As you can see the data gets repeated a few hundred times is there a way to fix this?
You can sum up passangers for city and destination.
SELECT Airport.city, StateInfo.state_name, TravelInfo.destination,
Carrier.unique_carrier_name
,sum( CarrierInfo.passengers) as passengers
FROM Airport
INNER JOIN TravelInfo
ON Airport.airport_id = TravelInfo.destination_airport_id
INNER JOIN Flights
ON Airport.airport_id = Flights.destination_airport_id
INNER JOIN StateInfo
ON Airport.airport_id = StateInfo.airport_id
INNER JOIN Carrier
ON Flights.airline_id = Carrier.airline_id
INNER JOIN CarrierInfo
ON Carrier.airline_id = CarrierInfo.airline_id
WHERE Airport.state = 'CO'
GROUP BY 1,2,3,4;
But I believe this would over report the passenger number because I see duplicate passangers in your output. So somewhere in your joins you are duplicating data.

How to improve the performance of a SQL query even after adding indexes?

I am trying to execute the following sql query but it takes 22 seconds to execute. the number of returned items is 554192. I need to make this faster and have already put indexes in all the tables involved.
SELECT mc.name AS MediaName,
lcc.name AS Country,
i.overridedate AS Date,
oi.rating,
bl1.firstname + ' ' + bl1.surname AS Byline,
b.id BatchNo,
i.numinbatch ItemNumberInBatch,
bah.changedatutc AS BatchDate,
pri.code AS IssueNo,
pri.name AS Issue,
lm.neptunemessageid AS MessageNo,
lmt.name AS MessageType,
bl2.firstname + ' ' + bl2.surname AS SourceFullName,
lst.name AS SourceTypeDesc
FROM profiles P
INNER JOIN profileresults PR
ON P.id = PR.profileid
INNER JOIN items i
ON PR.itemid = I.id
INNER JOIN batches b
ON b.id = i.batchid
INNER JOIN itemorganisations oi
ON i.id = oi.itemid
INNER JOIN lookup_mediachannels mc
ON i.mediachannelid = mc.id
LEFT OUTER JOIN lookup_cities lc
ON lc.id = mc.cityid
LEFT OUTER JOIN lookup_countries lcc
ON lcc.id = mc.countryid
LEFT OUTER JOIN itembylines ib
ON ib.itemid = i.id
LEFT OUTER JOIN bylines bl1
ON bl1.id = ib.bylineid
LEFT OUTER JOIN batchactionhistory bah
ON b.id = bah.batchid
INNER JOIN itemorganisationissues ioi
ON ioi.itemorganisationid = oi.id
INNER JOIN projectissues pri
ON pri.id = ioi.issueid
LEFT OUTER JOIN itemorganisationmessages iom
ON iom.itemorganisationid = oi.id
LEFT OUTER JOIN lookup_messages lm
ON iom.messageid = lm.id
LEFT OUTER JOIN lookup_messagetypes lmt
ON lmt.id = lm.messagetypeid
LEFT OUTER JOIN itemorganisationsources ios
ON ios.itemorganisationid = oi.id
LEFT OUTER JOIN bylines bl2
ON bl2.id = ios.bylineid
LEFT OUTER JOIN lookup_sourcetypes lst
ON lst.id = ios.sourcetypeid
WHERE p.id = #profileID
AND b.statusid IN ( 6, 7 )
AND bah.batchactionid = 6
AND i.statusid = 2
AND i.isrelevant = 1
when looking at the execution plan I can see an step which is costing 42%. Is there any way I could get this to a lower threshold or any way that I can improve the performance of the whole query.
Remove the profiles table as it is not needed and change the WHERE clause to
WHERE PR.profileid = #profileID
You have a left outer join on the batchactionhistory table but also have a condition in your WHERE clause which turns it back into an inner join. Change you code to this:
LEFT OUTER JOIN batchactionhistory bah
ON b.id = bah.batchid
AND bah.batchactionid = 6
You don't need the batches table as it is used to join other tables which could be joined directly and to show the id in you SELECT which is also available in other tables. Make the following changes:
i.batchidid AS BatchNo,
LEFT OUTER JOIN batchactionhistory bah
ON i.batchidid = bah.batchid
Are any of the fields that are used in joins or the WHERE clause from tables that contain large amounts of data but are not indexed. If so try adding an index on at time to the largest table.
Do you need every field in the result - if you could loose one or to you maybe could reduce the number of tables further.
First, if this is not a stored procedure, make it one. That's a lot of text for sql server to complile.
Next, my experience is that "worst practices" are occasionally a good idea. Specifically, I have been able to improve performance by splitting large queries into a couple or three small ones and assembling the results.
If this query is associated with a .net, coldfusion, java, etc application, you might be able to do the split/re-assemble in your application code. If not, a temporary table might come in handy.

Sql Outer Join: Extracting values from multible tables

I am extracting data from multiple tables. mt query is as follows:
SELECT p.Record_Num as RecordNum
,p.GCD_ID as GCDID
,p.Project_Desc as ProjectDesc
,p.Proponent_Name as ProponentName
,st.Station_Name as StationName
,p.OpCentre as OpCentre
,s.Sector_Name as SectorName
,p.PLZone as PLZone
,f.Feeder_Desc as FeederDesc
,d.DxTx_Desc as DxTx
,op.Op_Control_Desc as OpControl
,t.Type_Desc as Type
,c.Conn_Desc as ConnectionKV
,ss.Status_Desc as Status
,p.MW as MW
,p.Subject as Subject
,p.Ip_Num as IpNum
,p.H1N_ID as H1NID
,p.NOMS_Slip_Num as NomsSlipNum
,p.NMS_Updated as NmsUpdated
,p.Received_Date as ReceivedDate
,p.Actual_IS_Date as ActualISDate
,p.Scheduled_IS_Date as ScheduledIsDate
,stst.Station_Name as UpStation
,ff.Feeder_Desc as UpFeeder
,p.HV_Circuit as HVCircuit
,p.SIA_Required as SIAReqd
FROM Project_Detail p,
Station st, Sector s, Feeder f, DxTx d, Operational_Control op, Type t,
Connection_Kv c, Status ss, Station stst, Feeder ff
WHERE
p.Station_ID = st.Station_ID and
p.Sector_ID = s.Sector_ID and
p.Feeder = f.Feeder_ID and
p.DxTx_ID = d.DxTx_ID and
p.OpControl_ID = op.Op_Control_ID and
p.Type_ID= t.Type_ID and
p.ConnKV_ID = c.Conn_ID and
p.Status_ID = ss.Status_ID and
p.UP_Station_ID = stst.Station_ID and
p.UP_Feeder_ID = ff.Feeder_ID
The problem with this query is if it doesnot find an associated value in the second table, it doesnot show the row.
for example : every project has feeders. so if a project_detail table has a feederid which doesnot have an association in the feeder table, then it wont show the row. also, there are times when the feeders are not assigned to a project.
i think i have to use outer joins to get the values. but i cannot figure out how to do that.
please help.
SELECT *
FROM Project_Detail p
LEFT JOIN
Station st
ON p.Station_ID = st.Station_ID
LEFT JOIN
Sector s
ON p.Sector_ID = s.Sector_ID
…
You need LEFT OR FULL OUTER JOINS instead of the inner joins you are now using with your where clause.
SELECT p.Record_Num as RecordNum
,p.GCD_ID as GCDID
,p.Project_Desc as ProjectDesc
,p.Proponent_Name as ProponentName
,st.Station_Name as StationName
,p.OpCentre as OpCentre
,s.Sector_Name as SectorName
,p.PLZone as PLZone
,f.Feeder_Desc as FeederDesc
,d.DxTx_Desc as DxTx
,op.Op_Control_Desc as OpControl
,t.Type_Desc as Type
,c.Conn_Desc as ConnectionKV
,ss.Status_Desc as Status
,p.MW as MW
,p.Subject as Subject
,p.Ip_Num as IpNum
,p.H1N_ID as H1NID
,p.NOMS_Slip_Num as NomsSlipNum
,p.NMS_Updated as NmsUpdated
,p.Received_Date as ReceivedDate
,p.Actual_IS_Date as ActualISDate
,p.Scheduled_IS_Date as ScheduledIsDate
,stst.Station_Name as UpStation
,ff.Feeder_Desc as UpFeeder
,p.HV_Circuit as HVCircuit
,p.SIA_Required as SIAReqd
FROM Project_Detail p
LEFT OUTER JOIN Station st ON p.Station_ID = st.Station_ID
LEFT OUTER JOIN Sector s ON p.Sector_ID = s.Sector_ID
LEFT OUTER JOIN Feeder f ON p.Feeder = f.Feeder_ID
LEFT OUTER JOIN DxTx d ON p.DxTx_ID = d.DxTx_ID
LEFT OUTER JOIN Operational_Control op ON p.OpControl_ID = op.Op_Control_ID
LEFT OUTER JOIN Type t ON p.Type_ID= t.Type_ID
LEFT OUTER JOIN Connection_Kv c ON p.ConnKV_ID = c.Conn_ID
LEFT OUTER JOIN Status ss ON p.Status_ID = ss.Status_ID
LEFT OUTER JOIN Station stst ON p.UP_Station_ID = stst.Station_ID
LEFT OUTER JOIN Feeder ff ON p.UP_Feeder_ID = ff.Feeder_ID