I'm not super familiar with SQL but I know the basics. I was recently trying to replicate some logic form reports to SQL Server 2012. I started with the custom query from Webi (a reporting tool) and was trying to make a view from it in SQL.
Here is what the query look like:
SELECT
dimGlobalSalesAnalysisTbl.globalSalesAnalysisDesc,
dimGlobalShipDestinationCountryTbl.area,
dimGlobalShipDestinationCountryTbl.subarea,
dimGlobalCurrentProductTbl.sbuCodeDesc,
dimGlobalShipDateVw.shipDayOfWeekDesc,
sum(factSalesTblVw.globalSalesValue) AS 'Global Sales Value',
SUM(factSalesTblVw.salesUnitQuantity*GlobalFiles.dimCurrentGTINTbl.unitQty) AS 'Sales Unit Quantity'
FROM
dimGlobalCookCompaniesTbl INNER JOIN factSalesTblVw ON
(dimGlobalCookCompaniesTbl.globalCookCompanyID=factSalesTblVw.globalCookCompanyID)
INNER JOIN dimGlobalHistProductTbl ON (dimGlobalHistProductTbl.globalHistProductID=factSalesTblVw.globalHistProductID)
INNER JOIN dimGlobalCurrentProductTbl ON (dimGlobalHistProductTbl.globalCurrentProductID=dimGlobalCurrentProductTbl.globalCurrentProductID)
INNER JOIN dimGlobalHistShipCustomerTbl ON (factSalesTblVw.globalHistShipCustomerID=dimGlobalHistShipCustomerTbl.globalHistShipCustomerID)
INNER JOIN dimGlobalCurrentShipCustomerTbl ON (dimGlobalHistShipCustomerTbl.shipCustomerID=dimGlobalCurrentShipCustomerTbl.globalCurrentShipCustomerID)
***INNER JOIN dimGlobalCountryTbl dimGlobalShipDestinationCountryTbl ON (dimGlobalCurrentShipCustomerTbl.shipDestCountryDesc=dimGlobalShipDestinationCountryTbl.countryCode)***
INNER JOIN dimGlobalSalesAnalysisTbl ON (factSalesTblVw.globalSalesAnalysisID=dimGlobalSalesAnalysisTbl.globalSalesAnalysisID)
INNER JOIN dimGlobalShipDateVw ON (dimGlobalShipDateVw.shipJulianDate=factSalesTblVw.shipDateID)
INNER JOIN GlobalFiles.dimCurrentGTINTbl ON (GlobalFiles.dimCurrentGTINTbl.curGtinId=factSalesTblVw.GtinID)
WHERE
(
dimGlobalShipDateVw.shipYearNumber IN (DATEPART(yy,GETDATE())-1)
AND
dimGlobalCurrentShipCustomerTbl.shipCustomerNumberDesc
IN ( 'JPC000222-3','CNC000012-1' )
AND
dimGlobalSalesAnalysisTbl.globalSalesAnalysisDesc = 'Return Credits'
)
GROUP BY
dimGlobalShipDateVw.shipDate,
dimGlobalSalesAnalysisTbl.globalSalesAnalysisDesc,
dimGlobalShipDestinationCountryTbl.area,
dimGlobalShipDestinationCountryTbl.subarea,
dimGlobalCurrentProductTbl.sbuCodeDesc,
Upper(dimGlobalCurrentProductTbl.familyCodeDesc),
dimGlobalShipDateVw.shipYearNumber,
dimGlobalShipDateVw.shipDayOfWeekDesc,
dimGlobalCurrentProductTbl.madeByAbbr,
dimGlobalCookCompaniesTbl.companyDesc
This particular query runs on the production system if ran in the relevant database. When trying to make a view of this query in a different database, I precede the objects by [database_name].[schema/dbo] name.
On running the query, I get the error:
Invalid object name 'WWS.dbo.dimGlobalShipDestinationCountryTbl'
I try to find this particular table on the database, but it isn't there, though hovering over the table name in the query give a table definition but no script.
This table is present in an weird looking inner join (6th inner join) syntax like this:
INNER JOIN dimGlobalCountryTbl dimGlobalShipDestinationCountryTbl ON
(dimGlobalCurrentShipCustomerTbl.shipDestCountryDesc=dimGlobalShipDestinationCountryTbl.countryCode)
Two questions:
1. Can someone please explain this query syntax for inner join ?
2. This is pretty stupid but any ideas on how to look into possibly hidden table definitions ?
Two questions: 1. Can someone please explain this query syntax for inner join ?
The inner join in this case is nothing more than a table alias. The creator of the query thought aliasing the table would be easier to understand this name instead of the actual table name, or the same table is referenced twice and one would have to have an alias.
2. This is pretty stupid but any ideas on how to look into possibly hidden table definitions ?
Why? I think you just have a syntax error on your SQL when you added the database_name.schema syntax.
Think of the table alias like a column alias.... but and just like columns, you can omit the 'AS' keyword...
dimGlobalCountryTbl dimGlobalShipDestinationCountryTbl is the same as
dimGlobalCountryTbl AS dimGlobalShipDestinationCountryTbl
Related
I have 7 Tables as per attached following Image.
I will either enter Engine Number or Chassis Number and it should show the respective tables information (these tables have only mentioned fields) so all fields can be shown as result.
I can use hard coded Engine Number or Chassis Number. Every time of execution of this Query, I will hard code the required Engine/Chassis Number and will get the result.
Can anybody please help me to write this query for me?
Click Here to See the Tables
This might be a starting point for your solution.
SELECT prod.EngineNo AS engNo, prod.ChassisNo, doral.doralNo [, table.column [AS name]]
FROM DOProductSpecsDetais AS prod
INNER JOIN DORAL AS doral
ON prod.DOProductSpecsDetailID = doral.DOProductSpecsID
INNER JOIN DOProductDetail AS prodDetail
ON prod.DOProductDetailID = prodDetail.DOProductDetailID
WHERE prod.ChassisNo = '<input>' OR prod.EngineNo='<input>'
Between the SELECT and the FROM Statement, you can select any column out of your JOIN.
You can cascade as many JOINs as you like...
Which DBMS are you going to use?
One suggestion: Try to simplify the names of your columns, if possible.
One more: If you just started to do Database things, it is always helpful to start a test environment and use a client tool.
You can write query something like this:
select * from
DoProductSpecsDetail tbl1 inner join Doral tbl2
on tbl1.DoProductSpecsDetailId = tbl2.DoProductSpecsId
inner join DoproductDetail tbl3
on tbl1.DoProductDetailId = tbl3.DoProductDetailId
inner join ProductColor tbl4
on tbl1.ProductColorId = tbl4.ProductColorId
inner join DoDetail tbl5
on tbl3.DeliveryOrderDetailId = tbl5.DeliveryOrderId
inner join ProductMain tbl6
on tbl3.ProductId = tbl6.ProductId
inner join BPMain tbl7
on tbl5.BusinessPartnerId = tbl7.BusinessPartnerId
I have been googled some for an explanation of the SQL function ON though
I couldn't find a good explanation how it work.
is it associated/connected to INNER JOIN?
Could someone please explain my Code-snippet what really happens?
(see my code below)
SELECT
TS_TEST_ID as Test_ID,
TS_NAME as Name
FROM TEST
INNER JOIN DESSTEPS
ON TEST.TS_TEST_ID = DESSTEPS.DS_TEST_ID
INNER JOIN ALL_LISTS
ON ALL_LISTS.AL_ITEM_ID = TEST.TS_SUBJECT
It is not a function, it is part of language. Like with natural language you have various types of words: like nouns, verbs etc. This is like proposition.
ON is a part of syntax for INNER JOIN, it goes like this:
one table INNER JOIN some other table ON how do I want to join both tables (key columns)
You might find some more details here
on tells the join with which condition the tables should be connected.
In this case:
FROM TEST
INNER JOIN DESSTEPS
ON TEST.TS_TEST_ID = DESSTEPS.DS_TEST_ID
You tables test will be joined on column TS_TEST_ID and DS_TEST_ID. So records belong together, where These id's are equals
Please bear with me as this may be a question without a possible answer, but I hope I describe it correctly..
I have a query which joins a number of tables and produces results, and here is the SQL:
SELECT
dbo.Property.PropertyPK,
dbo.Tenancy.TenancyPK,
dbo.Tenant.ContactFK,
dbo.Contacts.strTitle,
dbo.Contacts.strFirstName,
dbo.Contacts.strSurname
FROM dbo.Property
INNER JOIN dbo.Tenancy ON dbo.Property.PropertyPK = dbo.Tenancy.PropertyFK
INNER JOIN dbo.Tenant ON dbo.Tenancy.TenancyPK = dbo.Tenant.TenancyFK
INNER JOIN dbo.Contacts ON dbo.Tenant.ContactFK = dbo.Contacts.ContactPK
The main table is the Property table and I filter out one row by specifying a PropertyPK in my criteria..
My question is.. If the Tenant or Contact record does not exist and I run my query in SQL Management Studio of course I get a message saying there are no rows but can I determine at what stage the join has failed between two tables?
I can of course check this in management studio but I am trying to help the user on the application side to inform them of why there are no rows. My application is in VB and I will write that check if there are no rows and I cannot determine it in SQL..
Sorry for the question in advance..
Derek.. :)
Simply use a LEFT JOIN:
SELECT p.PropertyPK, ty.TenancyPK, t.ContactFK,
c.strTitle, c.strFirstName, c.strSurname
FROM dbo.Property p LEFT JOIN
dbo.Tenancy ty
ON p.PropertyPK = ty.PropertyFK LEFT JOIN
dbo.Tenant t
ON ty.TenancyPK = t.TenancyFK LEFT JOIN
dbo.Contacts c
ON t.ContactFK = c.ContactPK;
This will keep all rows in the Property table. You can then see which primary keys are NULL to see if there were matches in the other tables.
Note that the query is much easier to write and to read when you use table aliases.
Can you guys help me please in understanding the SQL specifications on join. I don't understand it. I kept getting errors called Unknown column list on on clause.
I got this error over my SQL syntax, I almost rubbed it in my face I just can't understand why it is not working, I have read some article regarding that it is because of precedence etc but I am really confused on what I have done wrong here.
select product.name , product.price from product inner join product_category on
(product_category.product_no = product.product_no ) where product_category.sub_category =
"COFFIN";
I know this question have been ask a hudred and million times here, but the ones I saw are complicated nowhere close in this very basic sql syntax.
THanks for helping me out.
EDIT:
I just had realize that I have product_category not a direct child to my product table so
I just have typed
select * from product
join specifications
join product_category on ( specifications.product_no = product_category.product_no);
But this still gave me an error, unknown column product_category.
I've read and followed some instruction similarly to this sites:
MYSQL unknown clause join column in next join
Unknown column {0} in on clause
MySQL "Unknown Column in On Clause"
I am really frustrated. I really can't get it to work.
For each new table you join in your query, each table must have at least one ON clause. It's hard to know exactly what you're trying to do without knowing the schema (table names, columns, etc), but here's an example
select *
from product p
join specifications s
on p.product_no = s.product_no
join product_category pc
on pc.spec_no = p.spec_no
Check out this link on table aliases as well. Gives a good example on joins + really useful info on how to increase the readability of your SQL
http://msdn.microsoft.com/en-us/library/ms187455(v=sql.90).aspx
I found this article useful as well as it visually displays the different types of joins
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
You are missing the part where you specify the joining conditions between product and specifcations.
select * from product
join specifications YOU NEED SOMETHING HERE
join product_category on etc
I modified the SQL syntax to look like this, I have overlook a key that connects product_category onto specification so I made necessary link and it worked!!!
SELECT *
FROM product
JOIN specifications ON ( product.product_no = specifications.product_no )
JOIN product_category ON ( specifications.spec_no = product_category.spec_no )
WHERE product_category.sub_category = "COFFIN"
LIMIT 0 , 30
Also thanks for the heads up on missing joining condition on specifications. Heck this carelessness cost so much time.
Thank you so much!
The default join type is an inner join. So if you write join, the database reads inner join, and insist that you include an on clause.
If you'd like to join without a condition, specify the cross join explicitly:
select *
from product p
cross join
specifications s
inner join
product_category pc
on pc.product_no = p.product_no
left join
some_other_table sot
on 1=1
The last join, with the on 1=1 condition, is another way to do a cross join. It's subtly different in that it will return rows from the left table even if the right table is empty.
Example at SQL Fiddle.
I have a query which works, goes like this:
Select
count(InsuranceOrderLine.AntallPotensiale) as potensiale,
COUNT(InsuranceOrderLine.AntallSolgt) as Solgt,
InsuranceProduct.Name,
InsuranceProductCategory.Name as Kategori
From
InsuranceOrderLine, InsuranceProduct, InsuranceProductCategory
where
InsuranceOrderLine.FKInsuranceProductId = InsuranceProduct.InsuranceProductID
and InsuranceProduct.FKInsuranceProductCategory = InsuranceProductCategory.InsuranceProductCategoryID
Group by
InsuranceProduct.name, InsuranceProductCategory.Name
This query over returns what I need, but when I try to add more table (InsuranceOrder) to be able to get the regardingUser column, then all the count values are way high.
Select
count(InsuranceOrderLine.AntallPotensiale) as Potensiale,
COUNT(InsuranceOrderLine.AntallSolgt) as Solgt,
InsuranceProduct.Name,
InsuranceProductCategory.Name as Kategori,
RegardingUser
From
InsuranceOrderLine, InsuranceProduct, InsuranceProductCategory, InsuranceSalesLead
where
InsuranceOrderLine.FKInsuranceProductId = InsuranceProduct.InsuranceProductID
and InsuranceProduct.FKInsuranceProductCategory = InsuranceProductCategory.InsuranceProductCategoryID
Group by
InsuranceProduct.name, InsuranceProductCategory.Name,RegardingUser
Thanks in advance
You're adding one more table to your FROM statement, but you don't specify any JOIN condition for that table - so your previous result set will do a FULL OUTER JOIN (cartesian product) with your new table! Of course you'll get duplication of data....
That's one of the reasons that I'm recommending never to use that old, legacy style JOIN - do not simply list a comma-separated bunch of tables in your FROM statement.
Always use the new ANSI standard JOIN syntax with INNER JOIN, LEFT OUTER JOIN and so on:
SELECT
count(iol.AntallPotensiale) as Potensiale,
COUNT(iol.AntallSolgt) as Solgt,
ip.Name,
ipc.Name as Kategori,
isl.RegardingUser
FROM
dbo.InsuranceOrderLine iol
INNER JOIN
dbo.InsuranceProduct ip ON iol.FKInsuranceProductId = ip.InsuranceProductID
INNER JOIN
dbo.InsuranceProductCategory ipc ON ip.FKInsuranceProductCategory = ipc.InsuranceProductCategoryID
INNER JOIN
dbo.InsuranceSalesLead isl ON ???????? -- JOIN condition missing here !!
When you do this, you first of all see right away that you're missing a JOIN condition here - how is this new table InsuranceSalesLead linked to any of the other tables already used in this SQL statement??
And secondly, your intent is much clearer, since the JOIN conditions linking the tables are where they belong - right with the JOIN - and don't clutter up your WHERE clauses ...
It looks like you added the table join which slightly multiplies count of rows - make sure, that you properly joining the table. And be careful with aggregate functions over several joined tables - joins very often lead to duplicates