SQL between clause returns rows for values outside bounds - sql

As the title says when I use the sql between clause I am running it against an address range from low to high and I am putting in a number that is outside of the two and getting rows returned to me. And I would like to know why.
http://www.sqlfiddle.com/#!6/49467/2
Quick hit on the query, I am using an address number of 4929 and getting rows returned to me where the address range low and high numbers are 400 and 498 respectively.
Here is the query:
SELECT
ZipCodeLow ,
ZipCodeHigh ,
ZipExtensionLow ,
EndingEffectiveDate ,
BeginningEffectiveDate ,
AddressRangeLow ,
AddressRangeHigh ,
StreetName ,
City ,
ZipCode ,
Zip4,
Zip4High
FROM BoundTable
WHERE
('68503' BETWEEN ZipCodeLow AND ZipCodeHigh) AND
('4929' BETWEEN [AddressRangeLow] AND [AddressRangeHigh]) AND
([StreetName] = '32ND') AND
(GETDATE() BETWEEN [BeginningEffectiveDate] AND [EndingEffectiveDate])

Convert 4929 to numeric first and then run the query:
SELECT
ZipCodeLow ,
ZipCodeHigh ,
ZipExtensionLow ,
EndingEffectiveDate ,
BeginningEffectiveDate ,
AddressRangeLow ,
AddressRangeHigh ,
StreetName ,
City ,
ZipCode ,
Zip4,
Zip4High
FROM BoundTable
WHERE
('68503' BETWEEN ZipCodeLow AND ZipCodeHigh) AND
(convert(numeric,'4929') BETWEEN [AddressRangeLow] AND [AddressRangeHigh]) AND
([StreetName] = '32ND') AND
(GETDATE() BETWEEN [BeginningEffectiveDate] AND [EndingEffectiveDate])

Related

Can you explain the meaning of a minus in a SQL select statement?

I am working with SQL and I found this snippet, my question is: what does it mean those minus symbols (-) inside the select statement? I know is a kind of some trick, but I can't find information online about how it is used, please any insight would be welcome.
I am referring to:
SELECT - sum(st.sales) AS sales
- sum(st.orders) AS orders
- sum(st.aov) AS aov
It seems to be related to ledger tables, if you have any documentation, blog or pdf please give me the link to check it.
The full SQL looks like this:
INSERT INTO sales_test
WITH source_query AS --find the existing values in the ledger table and invert them
(
SELECT
st.og_date
, st.merchant
, st.store_name
, st.country
, st.kam
, st.class
, st.origin
, - sum(st.sales) AS sales
, - sum(st.orders) AS orders
, - sum(st.aov) AS aov
, et.source_file_name
, et.source_file_timestamp
FROM
sales_test st
INNER JOIN
ext_sales_test et
ON
city_hash(et.og_date, et.merchant, et.store_name, et.country, et.kam, et.class, et.origin) = city_hash(st.og_date, st.merchant, st.store_name, st.country, st.kam, st.class, st.origin)
AND st.og_date = et.og_date
AND st.merchant = et.merchant
GROUP BY
st.og_date
, st.merchant
, st.store_name
, st.country
, st.kam
, st.class
, st.origin
, et.source_file_name
, et.source_file_timestamp
)
, union_query AS --if we union the incoming data with the inverted existing data, we get the difference that needs to be ledgered
(
SELECT *
FROM
source_query
UNION ALL
SELECT *
FROM
ext_sales_text
)
It makes the numeric value negative(if numeric value is negative, - - is positive), in your case it first performs the sum and then it makes it negative or positive:
As an example:
USE tempdb;
GO
DECLARE #Num1 INT;
SET #Num1 = 5;
SELECT #Num1 AS VariableValue, -#Num1 AS NegativeValue;
GO
Result set:
VariableValue NegativeValue
------------- -------------
5 -5
(1 row(s) affected)
Further info here

An efficient way to group columns in MonetDB

I have the next INSERT with SELECT in MonetDB:`
insert into colombia.agregada_region_mes
(
cod_anomes
, cod_produto
, sg_estado
, cod_subcanal
, qtd_vendidas
, valor
, valor_dolar
, valor_euro
, fact_count
)
select
f.cod_anomes
, f.cod_produto
, f.sg_estado
, f.cod_subcanal
, sum(f.qtd_vendidas) as qtd_vendidas
, sum(f.valor) as valor
, sum(f.valor_dolar) as valor_dolar
, sum(f.valor_euro) as valor_euro
, count(*) as fact_count
from colombia.staging_rm_fact f
group by
f.cod_anomes
, f.cod_produto
, f.sg_estado
, f.cod_subcanal;
(Please, note the GROUP BY part).
Table "staging_rm_fact" has 50 million of rows, and MonetDB exceeds 16Gb of memory trying to resolve the INSERT:
Is there any other efficient way to resolve this group by?

Group by - Non-group-by expression in select clause

Sorry you will have to bear with me as i am relativly new to SQL. I am querying an ODBC in EXCEL. At the moment my dataset is massive so i am looking to narrow it down by grouping it by company name and date. not all my columns are calculated fields.I have put the Sum on the two i need adding up. When i try to return the data i get the error of Non-group-by expression in select clause
Please can someone help me out.
SELECT
SopOrder_0.SooOrderNumber
, Company_0.CoaCompanyName
, InvoiceCreditItem_0.InvoiceCreditItemID
, InvoiceCreditItem_0.IciInvoiceApproved
, InvoiceCreditItem_0.InvoiceCreditID
, InvoiceCreditItem_0.CompanySiteID
, InvoiceCreditItem_0.VatID
, InvoiceCreditItem_0.NominalID
, InvoiceCreditItem_0.IciCreatedDate
, Sum(InvoiceCreditItem_0.IciTotalNettValue)
, Sum(InvoiceCreditItem_0.IciVatValue)
FROM
SBS.PUB.Company Company_0
, SBS.PUB.Customer Customer_0
, SBS.PUB.InvoiceCreditItem InvoiceCreditItem_0
, SBS.PUB.SopOrder SopOrder_0
WHERE
SopOrder_0.SopOrderID = InvoiceCreditItem_0.SopOrderID
AND InvoiceCreditItem_0.CompanyID = Customer_0.CompanyID
AND InvoiceCreditItem_0.CompanyID = Company_0.CompanyID
AND (Company_0.CoaCompanyName<>'ATOS')
AND InvoiceCreditItem_0.IciCreatedDate >= ?
GROUP BY
Company_0.CoaCompanyName, InvoiceCreditItem_0.IciCreatedDate

consolidate rows in sql not working as it should

I am having this issue with making consolidate for rows, I have made the query, but the result aren't correct.
It may consolidate the rows but for some result it will divide them into two different rows , what i need is to make them all in one row only if the id
is matching.
And here is the query :
Select
trxTransactionSaleItem.TransactionKey
, 'Sale' As TrxnType
, InvProduct.Id
, InvProduct.UPC
, trxTransactionSaleItem.Description
, invproduct.Description2
, invProduct.ProductGroupKey
, sum (Quantity/ISNULL(UOMBaseQuantity,1)) as Quantity
, Price
, SUM(DiscountAmount) AS DA
, SUM(SurchargeTotal) AS ST
, sum (Total) as Total
, ISNULL(UOM.Description,'') as UOM
From
trxTransactionSaleItem
INNER JOIN
InvProduct on trxTransactionSaleItem.ProductKey = InvProduct.ProductKey
LEFT JOIN
InvUOMGroupDetail UOMD on UOMGroupDetailKey = UOMD.UOMGroupDetailKey
LEFT JOIN
InvUOM UOM on UOMD.UOMKey = UOM.UOMKey
Where
Type = 0
And IsExchange = 0
And trxTransactionSaleItem.TransactionKey = 60000000022537
group by
trxTransactionSaleItem.TransactionKey
, InvProduct.Id
, InvProduct.UPC
, trxTransactionSaleItem.Description
, invproduct.Description2
, invProduct.ProductGroupKey
, Quantity
, Price
, DiscountAmount
, SurchargeTotal
, Total
, UOM.Description
So why its not coming in one row ?
Your group by should have only the fields that are not in aggregation functions. It should look like:
group by trxTransactionSaleItem.TransactionKey,
InvProduct.Id,
InvProduct.UPC,
trxTransactionSaleItem.Description,
invproduct.Description2,
invProduct.ProductGroupKey,
Price,
ISNULL(UOM.Description, '')

Optimizing select query with DISTINCT

My query goes like this. If I just run the query without a distinct, it takes only 11 seconds. While it takes 46 seconds to run with distinct. Any advice on how this can be optimized?
SELECT * FROM (
SELECT DISTINCT ELIGIBLE_TO_SIGN_DT
, LAST_NAME
, FIRST_NAME
, EXTENDED_LAST_NAME
, DT_OF_BIRTH
, BIRTH_COUNTRY_ID
, REG_BY
, LAST_UPDATED_BY
, REVIEW_STATUS_1
, REVIEW_STATUS_2
, REVIEW_STATUS_3
, MLSB_MATCH_FILTER
, REG_STATUS_ID
, REG_STATUS
, HAS_TRAVELED
, PLAYER_ID_SHOW
, MLSB_MATCH
, TRAINER_AGENT_NAME
, NATIONAL_ID
, RES_FOLLOW_UP
, ATTACHMENT
, COMMENTS
, PLAYER_ID
, CHECKBOX
, INTL_AMA_ENTRY_ID
, ALSO_REG_BY
, MIDDLE_NAME
, BIRTH_COUNTRY_NAME
FROM AS_INTL_ADMIN_REG_VIEW
where VARCHAR_FORMAT(ELIGIBLE_TO_SIGN_DT, 'YYYY-MM-DD') >= date('07/02/2015') AND VARCHAR_FORMAT(ELIGIBLE_TO_SIGN_DT, 'YYYY-MM-DD') <= date('08/31/2015')
) order by case when UPPER(LAST_NAME) is null or trim(UPPER(LAST_NAME)) = '' then 'ZZZZZZ' else UPPER(LAST_NAME) end ASC, case when FIRST_NAME is null or trim(FIRST_NAME) = '' then 'ZZZZZZ' else FIRST_NAME end ASC
limit 200 offset 0
If the example as written is your actual code, then the difference is accounted for by the LIMIT you have on the query. When you run it without the DISTINCT, the query engine can just take the first 200 rows. But with the DISTINCT, it must first run on the entire table to find the distinct rows, then select the first 200.
DISTINCT is costly, ORDER BY ... UPPER()... can be costly
In the query given, it seems likely to me that DISTINCT is being used unnecessarily or to fix duplicates that shouldn't be there. If the data is bad, consider fixing it rather than working around it.
Make sure you have a case insensitive index built
create index myindex on mytable UPPER(LAST_NAME)