FYI – this query runs from excel. i have prompt fields to set date range.
here is the original working query i got from someone:
SELECT
SalesInvoiceItems.FreeTextItem, SalesInvoiceItems.Product,
SalesInvoiceItems.ItemDescription, SalesInvoiceItems.Quantity,
SalesInvoiceItems.ItemValue, Customers.CustomerId, Customers.CustomerName,
SalesInvoices.SalesInvoiceId, SalesInvoices.EffectiveDate, Countries.CountryId,
SalesInvoiceItems.ItemType
FROM
Winman.dbo.Countries Countries, Winman.dbo.Customers Customers,
Winman.dbo.Products Products, Winman.dbo.SalesInvoiceItems SalesInvoiceItems,
Winman.dbo.SalesInvoices SalesInvoices
WHERE
Customers.Customer = SalesInvoices.Customer
AND SalesInvoiceItems.SalesInvoice = SalesInvoices.SalesInvoice
AND Customers.Country = Countries.Country
AND ((SalesInvoices.SystemType='F')
AND (SalesInvoiceItems.ItemType<>'T')
AND (SalesInvoices.EffectiveDate>=? And SalesInvoices.EffectiveDate<=?)
AND (SalesInvoiceItems.ItemValue<>$0))
ORDER BY
SalesInvoiceItems.Quantity DESC
Important bit here is ItemType (it can only be T, wich is excluded, P – for products and N – for free text items)
I needed to add table Products, to retrieve ProductID. Obviously adding below code in WHERE clause:
AND Products.Product = SalesInvoiceItems.Product
will fail to bring up any free text item, as the aren’t products.
So I rewrote query with JOINs hoping that will solve my problem (bringing up both P and N type of entries):
SELECT
Products.ProductId,
SalesInvoiceItems.FreeTextItem,
SalesInvoiceItems.Product,
SalesInvoiceItems.ItemDescription,
SalesInvoiceItems.Quantity,
SalesInvoiceItems.ItemValue,
Customers.CustomerId,
Customers.CustomerName,
SalesInvoices.SalesInvoiceId,
SalesInvoices.EffectiveDate,
Countries.CountryId,
SalesInvoiceItems.ItemType
FROM
Winman.dbo.SalesInvoiceItems AS SalesInvoiceItems
INNER JOIN
Winman.dbo.Products AS Products ON Products.Product = SalesInvoiceItems.Product
INNER JOIN
Winman.dbo.SalesInvoices AS SalesInvoices ON SalesInvoices.SalesInvoice= SalesInvoiceItems.SalesInvoice
INNER JOIN
Winman.dbo.Customers AS Customers ON Customers.Customer = SalesInvoices.Customer
INNER JOIN
Winman.dbo.Countries AS Countries ON Countries.Country = Customers.Country
WHERE
((SalesInvoices.SystemType='F')
AND (SalesInvoiceItems.ItemType<>'T')
AND (SalesInvoices.EffectiveDate >= ? And SalesInvoices.EffectiveDate <= ?)
AND (SalesInvoiceItems.ItemValue <> $0)
)
ORDER BY
SalesInvoiceItems.Quantity DESC
but this still acts as AND – which ignores free text items! I’m obviously missing something.. how can I bring both products and free text items, despite that free text items don’t have ProductID ?
Your old query is using old style
JOINsyntax. It is a good thing to completely abandon this implicit (inner) joining in favor of explicit joining.When using explicit joins, you now have a choice between
INNERandOUTERjoins (ref. MSDN).So in response to your question, change your
INNER JOINs toLEFT JOINs