Return results on a calculated field based on two aggregate functions - sql

The SQL query returns the results i'm looking for however, i would like to exclude the results where balance (aliased field) equals zero, to reduce the set of results that appear.
I've using Where "balance" <> 0 and variations this, but keep getting error aggregation cannot be used in where clause. I tried nested selects as well, same error
SELECT "Item"."ItemCode"
,"ItmWhs"."WhsCode"
,"ItmWhs"."AvgPrice"
,"ItmWhs"."OnHand" AS "On Hand"
,"ItemGrp"."ItmsGrpNam"
,"Item"."ItmsGrpCod"
,"Item"."U_StyleCode"
,"Item"."U_StyleName"
,"Item"."U_ColourCode"
,"Item"."U_ColourName"
,"Item"."U_Size"
,"Item"."U_Gender"
,"Item"."U_LCC"
,SUM("Document"."InQty")
,SUM("Document"."OutQty")
,(SUM("Document"."InQty") - SUM("Document"."OutQty")) AS "Balance"
FROM "SBK_UA"."OINM" AS "Document"
,"SBK_UA"."OITW" AS "ItmWhs"
,"SBK_UA"."OITM" AS "Item"
INNER JOIN "SBK_UA"."OITB" AS "ItemGrp" ON "Item"."ItmsGrpCod" = "ItemGrp"."ItmsGrpCod"
WHERE "Document"."ItemCode" = "ItmWhs"."ItemCode"
AND "Document"."Warehouse" = "ItmWhs"."WhsCode"
AND "Item"."ItemCode" = "ItmWhs"."ItemCode"
AND "Document"."CreateDate" <= ?
GROUP BY "Item"."ItemCode"
,"ItmWhs"."WhsCode"
,"ItmWhs"."AvgPrice"
,"ItmWhs"."OnHand"
,"ItemGrp"."ItmsGrpNam"
,"Item"."ItmsGrpCod"
,"Item"."U_StyleCode"
,"Item"."U_StyleName"
,"Item"."U_Size"
,"Item"."U_ColourCode"
,"Item"."U_ColourName"
,"Item"."U_Gender"
,"Item"."U_LCC"
To return all the results except where the balance is zero.

You want a HAVING clause. After the GROUP BY add:
HAVING SUM("Document"."InQty") - SUM("Document"."OutQty") <> 0

Related

Self joining columns from the same table with calculation on one column not displaying column name

I am fairly new to SQL and having issues figuring out how to solve the simple issue below. I have a dataset I am trying to self-join, I am using (b.calendar_year_number -1) as one of the columns to join. I applied a calculation of -1 with the goal of trying to match values from the previous year. However, it is not working as the resulting column shows (No column name) with a screenshot attached below. How do I change the alias to b.calendar_year_number after the calculation?
Code:
SELECT a.day_within_fiscal_period,
a.calendar_month_name,
a.cost_period_rolling_three_month_start_date,
a.calendar_year_number,
b.day_within_fiscal_period,
b.calendar_month_name,
b.cost_period_rolling_three_month_start_date,
(b.calendar_year_number -1)
FROM [data_mart].[v_dim_date_consumer_complaints] AS a
JOIN [data_mart].[v_dim_date_consumer_complaints] AS b
ON b.day_within_fiscal_period = a.day_within_fiscal_period AND
b.calendar_month_name = a.calendar_month_name AND
b.calendar_year_number = a.calendar_year_number
I am using (b.calendar_year_number -1) as one of the columns to join.
Nope, you're not. Look at your join statement and you'll see the third condition is:
b.calendar_year_number = a.calendar_year_number
So just change that to include the calculation. As far as the 'no column name' issue, you can use colname = somelogic syntax or somelogic as colname. Below, I used the former syntax.
select a.day_within_fiscal_period,
a.calendar_month_name,
a.cost_period_rolling_three_month_start_date,
a.calendar_year_number,
b.day_within_fiscal_period,
b.calendar_month_name,
b.cost_period_rolling_three_month_start_date,
bCalYearNum = b.calendar_year_number
from [data_mart].[v_dim_date_consumer_complaints] a
left join [data_mart].[v_dim_date_consumer_complaints] b
on b.day_within_fiscal_period = a.day_within_fiscal_period
and b.calendar_month_name = a.calendar_month_name
and b.calendar_year_number - 1 = a.calendar_year_number;
You could use the analytical function LAG/LEAD to get your required result, no self-join necessary:
select a.day_within_fiscal_period,
a.calendar_month_name,
a.cost_period_rolling_three_month_start_date,
a.calendar_year_number,
old_cost_period_rolling_three_month_start_date =
LAG(cost_period_rolling_three_month_start_date) OVER
(PARTITION BY calendar_month_name, day_within_fiscal_period
ORDER BY calendar_year_number),
old_CalYearNum = LAG(calendar_year_number) OVER
(PARTITION BY calendar_month_name, day_within_fiscal_period
ORDER BY calendar_year_number)
from [data_mart].[v_dim_date_consumer_complaints] a

I have info on cycle counts in a warehouse that count the same locations multiple times. I want to get the latest NET_VAR for a specific location

I have used MAX(Date) and that will get me what i need until i put the qty in the mix, since they get different results after they fix things it has multiple answers and makes me group by the qty which in the end gives me multiple results. i just want the last count numbers.
SELECT (CH.MOD_DATE_TIME),LH.LOCN_BRCD ,DSP_SKU, (CH.ACTL_INVN_QTY-CH.EXPTD_QTY) "NET VAR" FROM CYCLE_COUNT_HIST CH , LOCN_HDR LH, ITEM_MASTER IM WHERE CH.WHSE = 'SH1' AND CH.LOCN_ID = LH.LOCN_ID AND CH.SKU_ID = IM.SKU_ID AND IM.CD_MASTER_ID = '147001' and DSP_SKU LIKE 'JBLBAR31BLKAM' AND LH.LOCN_BRCD = 'HAHK42A01' AND trunc(CH.CREATE_DATE_TIME) > SYSDATE-120
It returns 3 rows of results and I want the most recent line only. I plan to modify this to (select dsp_sku, sum(NET_VAR) in the end to run a summary of the sku.
I think you can use subquery.
You just need to put the following condition in where clause:
where .....
AND
CH.MOD_DATE_TIME = (select MAX( MOD_DATE_TIME)
from cycle_count_hist)

CASE and GROUP BY in SQL

I have been writing a query that allows me to select and count rows for specific product id's and shipment types.
Within this data, what I am now trying to achieve is count which rows have a specific field populated (second member name) and which have not. Then return this as a separate column in my query results.
Here's the query which I have written:
select count(job.JobID) as itemsCount, Lookup_Pack.PackDescription, Lookup_Pack.PackCode, Lookup_Pack.ID, job.shipping,
CASE
WHEN Job.secondMemForename <> '' THEN count(job.JobID)
ELSE 0
END AS [Extra card count]
from job
inner join Lookup_Pack on Lookup_Pack.ID = job.packTypeID
where Lookup_Pack.PackType = 'REN'
AND job.createDate >= '2015-06-01' and Job.createDate <= '2015-06-30'
GROUP BY Lookup_Pack.PackDescription, Lookup_Pack.PackCode, Lookup_Pack.ID, Job.shipping
If I run this query, I get an error returned as I am not grouping by Job.secondMemForename:
[FreeTDS][SQL Server]Column 'job.secondMemForename' is invalid in the
select list because it is not contained in either an aggregate
function or the GROUP BY clause.
although Job.secondMemForename does not form part of the query results.
I have subsequently added this field to the GROUP BY statement, the problem with this is that the data returned for all rows where the CASE applies is un-grouped as the Job.secondMemForename is different for all of them.
Any idea how I can resolve this?
Thanks.
Steeve.
Change Count() to Sum() and add it before CASE
SUM (CASE WHEN Job.secondMemForename <> '' THEN 1 END) AS [Extra card count]

single-row subquery returns more than one row. Query not working with main query

I hve to display several cell values into one cell. So I am using this query:
select LISTAGG(fc.DESCRIPTION, ';'||chr(10))WITHIN GROUP (ORDER BY fc.SWITCH_NAME) AS DESCRIP from "ORS".SWITCH_OPERATIONS fc
group by fc.SWITCH_NAME
It is working fine. But when I am merging this with my main(complete) query then I am getting the error as: Error code 1427, SQL state 21000: ORA-01427: single-row subquery returns more than one row
Here is my complete query:
SELECT
TRACK_EVENT.LOCATION,
TRACK_EVENT.ELEMENT_NAME,
(select COUNT(*) from ORS.TRACK_EVENT b where (b.ELEMENT_NAME = sw.SWITCH_NAME)AND (b.ELEMENT_TYPE = 'SWITCH')AND (b.EVENT_TYPE = 'I')AND (b.ELEMENT_STATE = 'NORMAL' OR b.ELEMENT_STATE = 'REVERSE'))as COUNTER,
(select COUNT(*) from ORS.SWITCH_OPERATIONS fc where TRACK_EVENT.ELEMENT_NAME = fc.SWITCH_NAME and fc.NO_CORRESPONDENCE = 1 )as FAIL_COUNT,
(select MAX(cw.COMMAND_TIME) from ORS.SWITCH_OPERATIONS cw where ((TRACK_EVENT.ELEMENT_NAME = cw.SWITCH_NAME) and (cw.NO_CORRESPONDENCE = 1)) group by cw.SWITCH_NAME ) as FAILURE_DATE,
(select LISTAGG(fc.DESCRIPTION, ';'||chr(10))WITHIN GROUP (ORDER BY fc.SWITCH_NAME) AS DESCRIP from "ORS".SWITCH_OPERATIONS fc
group by fc.SWITCH_NAME)
FROM
ORS.SWITCH_OPERATIONS sw,
ORS.TRACK_EVENT TRACK_EVENT
WHERE
sw.SEQUENCE_ID = TRACK_EVENT.SEQUENCE_ID
Not only are subqueries in the SELECT list required to return exactly one row (or any time they're used for a singular comparison, like <, =, etc), but their use in that context tends to make the database execute them RBAR - Row-by-agonizing-row. That is, they're slower and consume more resources than they should.
Generally, unless the result set outside the subquery contains only a few rows, you want to construct subqueries as part of a table-reference. Ie, something like:
SELECT m.n, m.z, aliasForSomeTable.a, aliasForSomeTabe.bSum
FROM mainTable m
JOIN (SELECT a, SUM(b) AS bSum
FROM someTable
GROUP BY a) aliasForSomeTable
ON aliasForSomeTable.a = m.a
This benefits you in other ways to - it's easier to get multiple columns out of the same table-reference, for example.
Assuming that LISTAGG(...) can be included with other aggregate functions, you can change your query to look like this:
SELECT Track_Event.location, Track_Event.element_name,
Counted_Events.counter,
Failure.fail_count, Failure.failure_date, Failure.descrip
FROM ORS.Track_Event
JOIN ORS.Switch_Operations
ON Switch_Operations.sequence_id = Track_Event.sequence_id
LEFT JOIN (SELECT element_name, COUNT(*) AS counter
FROM ORS.Track_Event
WHERE element_type = 'SWITCH'
AND event_type = 'I'
AND element_state IN ('NORMAL', 'REVERSE')
GROUP BY element_name) Counted_Events
ON Counted_Events.element_name = Switch_Operations.swicth_name
LEFT JOIN (SELECT switch_name,
COUNT(CASE WHEN no_correspondence = 1 THEN '1' END) AS fail_count,
MAX(CASE WHEN no_correspondence = 1 THEN command_time END) AS failure_date,
LISTAGG(description, ';' || CHAR(10)) WITHIN GROUP (ORDER BY command_time) AS descrip
FROM ORS.Switch_Operations
GROUP BY switch_name) Failure
ON Failure.switch_name = Track_Event.element_name
This query was written to (attempt to) preserve the semantics of your original query. I'm not completely sure that's what you actually need but without sample starting data and desired results, I have no way to tell how else to improve this. For instance, I'm a little suspicious of the need of Switch_Operations in the outer query, and the fact that LISTAGG(...) is run over row where no_correspondence <> 1. I did change the ordering of LISTAGG(...), because the original column would not have done anything (because the order way the same as the grouping), so would not have been a stable sort.
Single-row subquery returns more than one row.
This error message is self descriptive.
Returned field can't have multiple values and your subquery returns more than one row.
In your complete query you specify fields to be returned. The last field expects single value from the subquery but gets multiple rows instead.
I have no clue about the data you're working with but either you have to ensure that subquery returns only one row or you have to redesign the wrapping query (possibly using joins when appropriate).

Using Case Statement to replace value in one field based on value in a seperate field

I'm creating a report in SSRS and I can't use the IIF statement within the report to get the following done. I'm getting aggregate errors when I try to sum within the SSRS report.
`IIF(Fields!Period=0,0,IIF(Period=13,0,Balance/12))`
Works fine up until the moment I try to Sum.. get a silly aggregate error "Aggregate functions other than First, Last, Previous, Count, and Count Distinct can only aggregate data of a single data type"... These are all integers.
Basically I have a value in Master.Balance that I need to divide by 12 only when Secondary.Period equals 0 or 13. If Secondary.Period equals 0 or 13 then the value should be 0. I know my problem has to do with including the relationship between the tables, but I just don't know how to write that in.
Here is what I'm trying to use:
`CASE
WHEN Secondary.Period=0 OR Secondary.Period=13
THEN 0
ELSE Master.Balance/12
End As BudByPer`
Here is how the two tables are related to each other:
`FROM Master LEFT OUTER JOIN Secondary
ON Master.Project = Secondary.Project
AND Master.object = Secondary.object
AND Master.org = Secondary.org
`
How do I get the above into this:
SELECT DISTINCT Master.Project, Master.Object, Master.Fund, Master.Segment, Master.Balance, Secondary.project, Secondary.object, Secondary.org, Secondary.Period, Secondary.object, Secondary.Project.
FROM Master LEFT OUTER JOIN Secondary
ON Master.Project = Secondary.Project
AND Master.object = Secondary.object
AND Master.org = Secondary.org
WHERE (Master.object>=600000)
ORDER BY [Master.Fund]
You just need a select, it looks fine to me...
SELECT
Master.account,
Master.segment,
Secondary.desc,
Secondary.bud,
Segment.Num,
Segment.office,
CASE
WHEN Secondary.Period=0 OR Secondary.Period=13 THEN 0
ELSE Master.Balance/12
End As BudByPer
FROM Master
LEFT JOIN Secondary
ON Master.Project = Secondary.Project
AND Master.object = Secondary.object
AND Master.org = Secondary.org