how to stop INNER JOIN from showing repeat data - sql

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.

Related

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 can I display tablenames in resultheader of SQL Server 2008 query

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";

Oracle (Netsuite) SQL one join limit results

I have an oracle SQL query and a slight problem. I need to check if an item has a PO# that it has at least 1 line item. The query below works however it returns a result for each line of transaction_lines and I need only une result. PS I tried DISTINCT but get an ODBC error.
SELECT ITEMS.NAME, INVENTORY_NUMBER.INVENTORY_NUMBER, INVENTORY_NUMBER.ON_HAND_COUNT, ITEMS.SALESDESCRIPTION, CONDITION.LIST_ITEM_NAME,
BRAND_PARTNER.LIST_ITEM_NAME, PPROGRAM.LIST_ITEM_NAME, ENTITY.NAME, PO.TRANSACTION_NUMBER, INVENTORY_NUMBER.RECEIVED_COST, ITEMS.SALESPRICE, IR.TRANSACTION_NUMBER,
INVENTORY_SOURCE.LIST_ITEM_NAME, LOCATIONS.NAME, INVENTORY_NUMBER.RECEIPT_DATE, PO.INTERNAL_MEMO, INVENTORY_NUMBER.REFERENCE_, TEST_RESULTS.LIST_ITEM_NAME,
INVENTORY_NUMBER.TEST_FILE_LINK, INVENTORY_NUMBER.CONNECT_TRADE_ID, INVENTORY_NUMBER.SOLD_DATE, INVENTORY_NUMBER.SOLD_PRICE, INVENTORY_NUMBER.MEMO, ITEMS.UPC_CODE, ITEMS.MPN,
ITEMS.ITEM_ID, INVENTORY_NUMBER.CLEI, INVENTORY_NUMBER.CERTIFICATION_REF_ID
FROM INVENTORY_NUMBER
INNER JOIN ITEMS ON INVENTORY_NUMBER.ITEM_ID = ITEMS.ITEM_ID
INNER JOIN TRANSACTIONS AS PO ON INVENTORY_NUMBER.PURCHASE_ORDER_ID = PO.TRANSACTION_ID
INNER JOIN TRANSACTIONS AS IR ON INVENTORY_NUMBER.ITEM_RECEIPT_ID = IR.TRANSACTION_ID
INNER JOIN TRANSACTION_LINES ON PO.TRANSACTION_ID = TRANSACTION_LINES.TRANSACTION_ID
INNER JOIN ENTITY ON TRANSACTIONS.ENTITY_ID = ENTITY.ENTITY_ID
INNER JOIN CONDITION ON INVENTORY_NUMBER.CONDITION_ID = CONDITION.LIST_ID
INNER JOIN BRAND_PARTNER ON INVENTORY_NUMBER.BRAND_PARTNER_ID = BRAND_PARTNER.LIST_ID
INNER JOIN PPROGRAM ON INVENTORY_NUMBER.PROGRAM_ID = PPROGRAM.LIST_ID
INNER JOIN INVENTORY_SOURCE ON INVENTORY_NUMBER.INVENTORY_SOURCE_ID = INVENTORY_SOURCE.LIST_ID
INNER JOIN LOCATIONS ON INVENTORY_NUMBER.LOCATION_ID = LOCATIONS.LOCATION_ID
INNER JOIN TEST_RESULTS ON INVENTORY_NUMBER.TEST_RESULTS_ID = TEST_RESULTS.LIST_ID
WHERE INVENTORY_NUMBER.ON_HAND_COUNT IS NOT NULL AND ((INVENTORY_NUMBER.PURCHASE_ORDER_ID IS NULL) OR (INVENTORY_NUMBER.PURCHASE_ORDER_ID IS NOT NULL AND TRANSACTION_LINES.TRANSACTION_LINE_ID IS NOT NULL))
you could also remove the join to the transaction_lines and instead of tl.TRANSACTION_LINE_ID IS NOT NULL use an exists clause
and exists (select 1 from transaction lines tl
where tl.transaction_id = po.transaction_id)
I would suggest using a GROUP BY to help limit your results. You could also if you are interacting with transactions in your query you must always remember that without limiting results based on the "main line" you will receive the header record and then a record for each individual line item.
If you were doing this with a saved search you could put the criteria as "main line = true". Since I don't understand your query entirely I can't advise where to put this limitation in.

SQL Query to retrieve single record per filter

I have the following query:
SELECT min(salesorder.SOM_SalesOrderID) AS salesorder,
Item.IMA_ItemID,
Item.IMA_ItemName,
Customer.CUS_CorpName,
WK.WKO_WorkOrderID,
min(WK.WKO_OrigRequiredDate),
WK.WKO_WorkOrderTypeCode,
min(WK.WKO_RequiredDate),
max(WK.WKO_LastWorkDate),
min(wk.WKO_RequiredQty),
wk.WKO_MatlIssueDate,
min(SalesOrderDelivery.SOD_RequiredQty),
Item.IMA_ItemTypeCode,
Item.IMA_OnHandQty,
min(SalesOrderDelivery.SOD_PromiseDate),
min(WO.woo_operationseqID) AS seqid
FROM SalesOrder
INNER JOIN SalesOrderLine ON SalesOrder.SOM_RecordID = SalesOrderLine.SOI_SOM_RecordID
INNER JOIN SalesOrderDelivery ON SalesOrderLine.SOI_RecordID = SalesOrderDelivery.SOD_SOI_RecordID,
WO.
INNER JOIN Item ON SalesOrderLine.SOI_IMA_RecordID = Item.IMA_RecordID
INNER JOIN WKO wk ON Item.IMA_ItemID = WK.WKO_ItemID
INNER JOIN Customer ON SalesOrder.SOM_CUS_RecordID = Customer.CUS_RecordID
INNER JOIN woo WO ON WO.WOO_WorkOrderID = WK.WKO_WorkOrderID
WHERE wk.WKO_StatusCode = 'Released'
AND WO.WOO_StatusCode IS NULL
AND SalesOrderDelivery.SOD_ShipComplete = 'false'
GROUP BY WK.WKO_WorkOrderID,
Item.IMA_ItemID,
Item.IMA_ItemName,
Customer.CUS_CorpName,
WK.WKO_WorkOrderTypeCode,
wk.WKO_MatlIssueDate,
Item.IMA_ItemTypeCode,
Item.IMA_OnHandQty
I need 1 record returned for each wk.wko_workorderid. There is a field that is not included that I'm not sure how to get. I need to retrieve the woo.woo_workcenterid that corresponds to min(WO.woo_operationseqID)as seqid. I cannot include it in the general query since there are multiple workcenterids in the table and I only want the specific one that is part of the min operation sequence record.
Any help would be appreciated.

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