I'm trying to build a query in MS Access and having an issue figuring out the best way to build it. What I'm trying to do is is make sure all the Higher retails match within a set of matching pack numbers. For example:
PackNum Prefix Retail
6451618 DF 37.99
6451618 SK 37.99
6451618 VJ 34.99
6451618 SG 37.99
One of the group is off and I want the query to show it.
I was attempting to use something like this to have check but I'm not getting the results I'm looking for
IIf([dbo_PIC704Current]![PackNum]=[dbo_PIC704Current]![PackNum]
And [dbo_PIC704Current]![Ret2]<>[dbo_PIC704Current]![Ret2],True,False)
Any help or push in the right direction would be greatly appreciated!
-Deke
SELECT dbo_pic704current.packnum
, Min(dbo_pic704current.Ret2) AS LowRet2
, Max(dbo_pic704current.Ret2) AS HighRet2
, dbo_CatalogInfo.MediaId
, dbo_pic704current.DiscountReasonCode
, dbo_CatalogInfo.Brand
FROM dbo_pic704current INNER JOIN dbo_CatalogInfo ON (dbo_pic704current.year =
dbo_CatalogInfo.mailyear) AND (dbo_pic704current.catid = dbo_CatalogInfo.catalog)
WHERE (((dbo_CatalogInfo.MediaId)='CAT Catalog'))
GROUP BY dbo_pic704current.packnum, dbo_CatalogInfo.MediaId,
dbo_pic704current.DiscountReasonCode, dbo_CatalogInfo.Brand, dbo_pic704current.Year
HAVING (((Min(dbo_pic704current.Ret2))<>Max([Ret2])))
ORDER BY dbo_pic704current.packnum;
Your existing solution using aggregation is likely to yield better performance, but to offer an alternative, here is an example using a correlated subquery:
select
pc.packnum, pc.ret2, ci.mediaid, pc.discountreasoncode, ci.brand
from
dbo_pic704current pc inner join dbo_cataloginfo ci on
pc.year = ci.mailyear and pc.catid = ci.catalog
where
ci.mediaid = 'cat catalog' and exists
(select 1 from dbo_pic704current t where t.packnum = pc.packnum and t.ret2 > pc.ret2)
order by
pc.packnum
Related
So, I have Hibernate 5.3.1 in a project which connects to different enginees (MySql, Oracle, PostgreSQL and MS SQL), so I can't use native queries.
Let's say I have 3 records in a table, which all of them have the same datetime, but I need to group them only by date (not time). For example, 2019-12-04;
I execute this query:
SELECT
CONCAT(year(tx.date_), month(tx.date_), day(tx.date_)),
iss.code,
COUNT(tx.id)
FROM
tx_ tx
JOIN
issuer_ iss
ON
tx.id_issuer = iss.id
GROUP BY
CONCAT(year(tx.date_), month(tx.date_), day(tx.date_)), iss.code
But, when I test it connected to SQL SERVER 2017, instead of return 20191204, it's returning 2035. In Oracle and MySQL is working fine.
Anyone has any idea why is this happen? I've tried different ways, like use + instead of CONCAT but the result is the same.
I've also tried to extract them for separate (without concat), and they have been returning correct. The problem is, I need to group them by the complete date.
And just for the record, the field is declared as datetime2 in DDBB
How about simply adding them, instead of using CONCAT.
(year(tx.date_)*10000 + month(tx.date_)*100 + day(tx.date_)*1) AS datenum
Thus, try this:
SELECT
CAST((year(tx.date_)*10000 + month(tx.date_)*100 + day(tx.date_)*1) AS string) AS datenum,
iss.code
FROM tx_ tx
JOIN issuer_ iss
ON tx.id_issuer = iss.id
GROUP BY year(tx.date_), month(tx.date_), day(tx.date_), iss.code
Thanks for the hint Gert Arnold gave me. I just didn't realize that the query was adding like if they were numbers in MSSQL.
Finally, I manage to make it work in the 4 RDBMS casting to string first
SELECT
CONCAT(CAST(year(tx.date_) AS string), CAST(month(tx.date_) AS string), CAST(day(tx.date_) AS string)),
iss.code
FROM
tx_ tx
JOIN
issuer_ iss
ON
tx.id_issuer = iss.id
GROUP BY
CONCAT(year(tx.date_), month(tx.date_), day(tx.date_)), iss.code
I tried also casting to TEXT, but it throws exception in MySQL
Why use concat() to begin with?
Assuming Hibernate takes care of converting the non-standard year(), month() and day() functions, then the following should work on any DBMS
SELECT year(tx.date_), month(tx.date_), day(tx.date_), iss.code
FROM tx_ tx
JOIN issuer_ iss ON tx.id_issuer = iss.id
GROUP BY year(tx.date_), month(tx.date_), day(tx.date_), iss.code
I'm quite new to SQL server and basically I have this query that uses two table and I was wondering if there's an easy way to shorten the code, the repeating of the table names looks pretty bad.
SELECT
dbo.atbl_Sales_OrdersLines.OrderID, dbo.atbl_Sales_OrdersLines.Created,
dbo.atbl_Sales_OrdersLines.CreatedBy, dbo.atbl_Sales_OrdersLines.Updated,
dbo.atbl_Sales_OrdersLines.UpdatedBy,
dbo.atbl_Sales_OrdersLines.CUT, dbo.atbl_Sales_OrdersLines.CDL,
dbo.atbl_Sales_OrdersLines.Domain, dbo.atbl_Sales_OrdersLines.ProductID,
dbo.atbl_Sales_OrdersLines.Amount, dbo.atbl_Sales_Products.ProductName,
dbo.atbl_Sales_Products.Supplier, dbo.atbl_Sales_Products.Quantity AS TotalQuantity,
dbo.atbl_Sales_Products.Price, dbo.atbl_Sales_OrdersLines.PrimKey
FROM
dbo.atbl_Sales_OrdersLines
INNER JOIN
dbo.atbl_Sales_Products ON dbo.atbl_Sales_OrdersLines.ProductID = dbo.atbl_Sales_Products.ProductID
There has to be an easier way to do this. Thank you.
Use tables alias to shorten that code:
SELECT
ol.OrderID,
ol.Created, ol.CreatedBy, ol.Updated, ol.UpdatedBy,
ol.CUT, ol.CDL,
ol.Domain, ol.ProductID, ol.Amount,
p.ProductName, p.Supplier, p.Quantity AS TotalQuantity, p.Price,
ol.PrimKey
FROM
dbo.atbl_Sales_OrdersLines ol
INNER JOIN
dbo.atbl_Sales_Products p ON ol.ProductID = p.ProductID
The ol and p are table alias that you can choose - I recommend choosing something that is "intuitive", e.g. "ol" for "Order Lines", "p" for "Product" - that makes reading (and understanding) your SQL code much easier
I need to make hierarchical queries, and I need to get the results of CONNECT_BY_ISCYCLE and CONNECT_BY_ISLEAF, but these features are supported in Oracle not in Snowflake.
What are the alternative ways to implement the functionalities of CONNECT_BY_ISCYCLE and CONNECT_BY_ISLEAF in snowflake without using them as these keywords are not supported there?
Wonder if you have taken a look at the following Snowflake features?
https://docs.snowflake.net/manuals/user-guide/queries-hierarchical.html#using-connect-by-or-recursive-ctes-to-query-hierarchical-data
Yes I took a look there. I also took a look at https://docs.snowflake.net/manuals/sql-reference/constructs/connect-by.html where it clearly says that these features are not supported in Snowflake.
I was trying below code block to find an alternative but facing varieties of error in snowflake.
person_vertex as (
select
emp_number,
user_id
from person
),
person_edges as (
select
supervisor_emp_number,
emp_number
from person
where supervisor_emp_number is not null
),
select
pv.emp_number emp_id_pk,
level,
CONNECT_BY_ROOT pv.emp_number AS root,
concat(SYS_CONNECT_BY_PATH(pv.emp_number,':'),':') as path,
-- CONNECT_BY_ISCYCLE AS iscyclic, ------------------- no idea how to implement this
-- CONNECT_BY_ISLEAF as isleaf ------------------- i tried below block, but it is not working
case
when (pe.supervisor_emp_number in (select emp_number from pv)) then 0
else 1
end AS isleaf
from person_vertex pv
left join person_edges pe on pv.emp_number = pe.emp_number
connect by prior A.emp_number = A.supervisor_emp_number
start with A.supervisor_emp_number is null
Any help with this block is really appreciated.
Thanks.
enter code here
Recently I ran into an issue where we have multiple concurrent client requests causing performance issue in db. I tried the test scenario and as it turned out, when I run SELECT queries (same query) 6 to 7 times (gets worse with more), It degrades the performance and execution takes a lot of time. However I tried this one
SELECT TOP (100) COUNT(DISTINCT([Doc_Number])) AS "Expression"
FROM (
SELECT *
FROM "dbo"."Dummy_Table" "table_alias"
WHERE ((CAST("table_alias"."ID" AS NVARCHAR)) NOT IN
(
SELECT "PrimaryKey" AS ExceptionKey
FROM dbo.exceptions inner_exceptionStatus
LEFT JOIN dbo.Workflow inner_workflowStates ON
(inner_exceptionStatus."Status"= inner_workflowStates."UUID" AND
inner_exceptionStatus."UUID"= 'CA1662D6-73A2-4692-A765-E7E3EDB66062')
WHERE ("inner_workflowStates"."RemoveFromRecordSet" = 1 AND
"inner_workflowStates"."IsDeleted" = 0) AND
("inner_exceptionStatus"."IsArchived" IS NULL OR
"inner_exceptionStatus"."IsArchived" = 0)))) wrapperQuery
The query when runs alone takes around 1sec execution time. But If we runs it in parallel, for each query it takes up a wried amount of time of leads to timeout.
The only thing bothers me here is that SELECT query should be non-blocking and even with shared lock, then need to get along easily.
I am not sure if there is anything wrong in the query that adds up the situation.
Any help is deeply appreciated !!
Try this way
SELECT Count(DISTINCT( [Doc_Number] )) AS Expression
FROM dbo.Dummy_Table table_alias
WHERE NOT EXISTS (SELECT 1
FROM dbo.exceptions inner_exceptionStatus
INNER JOIN dbo.Workflow inner_workflowStates
ON ( inner_exceptionStatus.Status = inner_workflowStates.UUID
AND inner_exceptionStatus.UUID = 'CA1662D6-73A2-4692-A765-E7E3EDB66062' )
WHERE inner_workflowStates.RemoveFromRecordSet = 1
AND inner_workflowStates.IsDeleted = 0
AND ( inner_exceptionStatus.IsArchived IS NULL
OR inner_exceptionStatus.IsArchived = 0 )
AND table_alias.ID = PrimaryKey)
Made couple of changes.
Changed NOT IN to NOT EXISTS
Removed the convert in "table_alias"."ID" because it will avoid using any index present in "table_alias"."ID" column. If the conversion is really required then add it.
Removed Top (100) since there is no Group By it will return a single record as result.
Still if the query is running slow then you need to post the execution plan and make sure the statistics are up-to-date
You can simplyfy your query like this :
SELECT COUNT(DISTINCT(Doc_Number)) AS Expression
FROM dbo.Dummy_Table dmy
WHERE not exists
(
SELECT *
FROM dbo.exceptions ies
INNER JOIN dbo.Workflow iws ON ies.Status= iws.UUID AND ies.UUID= 'CA1662D6-73A2-4692-A765-E7E3EDB66062'
WHERE iws.RemoveFromRecordSet = 1 AND iws.IsDeleted = 0 AND (ies.IsArchived IS NULL OR ies.IsArchived = 0)
and dmy.ID=PrimaryKey
)
Like prdp say :
Changed NOT IN to NOT EXISTS
Removed the convert in "table_alias"."ID" because it will avoid using any index present in "table_alias"."ID" column. If the conversion is really required then add it.
Removed Top (100) since there is no Group By it will return a single record as result.
I add :
Remove you temporary table wrapperQuery
You can use INNER JOIN because into where you test RemoveFromRecordSet = 1 then you remove null values.
Remove not utils quotes ,brackets and parenthèses into where clause
I have a simple model where I would like to find some count data per date.
I made this find in order to do that:
$statsubscriptions = $this->Nlist->Statsubscription->find('all',
array(
'fields'=>array('Statsubscription.date','Statsubscription.type','COUNT(*) as qs'),
'qroup'=>array('Statsubscription.date','Statsubscription.type'),
'conditions'=>array('Statsubscription.nlist_id'=>$id),
'recursive'=>-1,
)
);
But it does not work. The generated query is the following:
SELECT `Statsubscription`.`date`, `Statsubscription`.`type`, COUNT(*) as qs
FROM `statsubscriptions` AS `Statsubscription`
WHERE `Statsubscription`.`nlist_id` = 1
GROUP BY is completly missing... Instead of the above I would like this query to be generated:
SELECT `Statsubscription`.`date`, `Statsubscription`.`type`, COUNT(`Statsubscription`.`id`) as qs
FROM `statsubscriptions` AS `Statsubscription`
WHERE `Statsubscription`.`nlist_id` = 1
GROUP BY `Statsubscription`.`date`, `Statsubscription`.`type`
How can I achieve this? And what could be the reason of the missing GROUP BY?
You are writing qroup instead of group (that's q instead of g). Which is why it doesn't work.
P.S.: get some sleep...