Aggregate function results in select statement - sql

Hopefully the code below should demonstrate what I'm trying to achieve.
The issue is that none of the input selects are resolved by the time I try to calculate VatableCash so I get "Invalid Column" when trying to select it.
Sorry if there's something plainly obvious I can do here. SQL isn't one of my strong suits.
select
OrderHeader.ID,
sum(OrderLine.NetPrice) as OrderLineNetPrice,
sum(OrderLine.GrossPrice) as OrderLineGrossPrice,
sum(
case when PaymentOption_ID = 8
then Payment.Amount
else 0
end
) as TotalCashAmount,
((OrderLineGrossPrice - OrderLineNetPrice) / OrderLineGrossPrice) * TotalCashAmount as VatableCash
from OrderHeader
inner join Payment on Payment.OrderHeader_ID = OrderHeader.ID
inner join OrderLine on OrderLine.OrderHeader_ID = OrderHeader.ID
group by OrderHeader.ID

You need to use sub query.
you can try this.
;WITH CTE AS
(
select
OrderHeader.ID,
sum(OrderLine.NetPrice) as OrderLineNetPrice,
sum(OrderLine.GrossPrice) as OrderLineGrossPrice,
sum(
case when PaymentOption_ID = 8
then Payment.Amount
else 0
end
) as TotalCashAmount
from OrderHeader
inner join Payment on Payment.OrderHeader_ID = OrderHeader.ID
inner join OrderLine on OrderLine.OrderHeader_ID = OrderHeader.ID
group by OrderHeader.ID
)
SELECT *,
((OrderLineGrossPrice - OrderLineNetPrice) / OrderLineGrossPrice) * TotalCashAmount as VatableCash
FROM CTE

Love the cross apply! Use it whenever you want some handy extra columns.
select
OrderHeader.ID,
sum(OrderLine.NetPrice) as OrderLineNetPrice,
sum(OrderLine.GrossPrice) as OrderLineGrossPrice,
TotalCashAmount,
((OrderLineGrossPrice - OrderLineNetPrice) / OrderLineGrossPrice) * TotalCashAmount as VatableCash
from OrderHeader
inner join Payment on Payment.OrderHeader_ID = OrderHeader.ID
inner join OrderLine on OrderLine.OrderHeader_ID = OrderHeader.ID
cross apply ( select sum(
case when PaymentOption_ID = 8
then Payment.Amount
else 0
end
)) as subquery(TotalCashAmount)
group by OrderHeader.ID

Related

Find a Subset of Records or Find All

I'm working on a similar problem to check if a column contains ALL the values of another column - Mysql
This CTE is part of a bigger query. CTE_ProjekteRollen contains a subset of ProjektParamRolle and can contain zero or more records. I want a list of ProjektParam where the items in CTE_ProjekteRollen are all present (when joined with ProjektParamRolle). My solution works in all cases where CTE_ProjektRollen is not empty.
CTE_FilteredByRolle as (
select pp.ID_ProjektParam
from Basis.ProjektParam pp
join Basis.ProjektParamRolle ppr
on pp.ID_ProjektParam = ppr.ID_ProjektParam
join CTE_ProjektRollen pr
on ppr.Rolle = pr.Rolle
group by pp.ID_ProjektParam
having Count(pp.ID_ProjektParam) = (
select Count(Rolle)
from CTE_ProjektRollen))
What do I have to change to get all ProjektParam (joined with ProjektParamRolle), if CTE_ProjektRollen is empty?
Edit: I think I phrased my question wrong, because I didn't understand it fully. #Kendle's solution works for what I described, but I actually needed all ID_ProjektParam (not joined with ProjektParamRolle).
The actual CTE that worked for me was
CTE_FilteredByRolle as (
select pp.ID_ProjektParam
from Basis.ProjektParam pp
where (
select Count(ppr.Rolle)
from Basis.ProjektParamRolle ppr
join CTE_ProjektRollen pr
on ppr.Rolle = pr.Rolle
where ppr.ID_ProjektParam = pp.ID_ProjektParam) = (
select Count(Rolle)
from CTE_ProjektRollen))
We can use a CASE to check whether the table is empty. If it is empty we return the number to which we are comparing, so it will always be true.
CTE_FilteredByRolle as (
select pp.ID_ProjektParam
from Basis.ProjektParam pp
join Basis.ProjektParamRolle ppr
on pp.ID_ProjektParam = ppr.ID_ProjektParam
join CTE_ProjektRollen pr
on ppr.Rolle = pr.Rolle
group by pp.ID_ProjektParam
having Count(distinct pp.ID_ProjektParam)
= case when(select Count(distinct Rolle) from CTE_ProjektRollen)) = 0
then Count(distinct pp.ID_ProjektParam)
else (select Count(distinct Rolle) from CTE_ProjektRollen))
end;

SQL Error when using LIKE CASE WHEN with subquery

I'm attempting to write an SQL statement that use Excel parameters to insert data via a drop down menu. This normally works great, but I think because I'm using a subquery in this case I'm getting the error "The multi-part identifier could not be bound." The subquery is used to create a sum of the quantity of an item purchased within the past week. Here's the code:
SELECT DISTINCT ITMMASTER.ITMREF_0 AS ITEMCODE, ITMMASTER.ITMDES1_0 AS ITEMDESC, Sum(ITMMVT.PHYSTO_0) AS AVAILSTOCK, Sum(ITMMVT.ORDSTO_0) AS ONORDER, Sum(ITMMVT.PHYALL_0) AS ALLOCATED, Sum(ITMFACILIT.MAXSTO_0) AS MAX,
INVQTY = (SELECT Sum(SINVOICED.QTY_0) AS INVQTY
FROM x3v11.PROD.SINVOICED SINVOICED
WHERE SINVOICED.INVDAT_0 BETWEEN DATEADD(WEEK,-1,DATEADD(WEEK,DATEDIFF(WEEK,0,GETDATE()),0))
AND DATEADD(DAY,4,DATEADD(WEEK,-1,DATEADD(WEEK,DATEDIFF(WEEK,0,GETDATE()),0)))
AND SINVOICED.ITMREF_0 = ITMMASTER.ITMREF_0
),
ITMMASTER.ITMWEI_0 AS WEIGHT, ITMCOST.CSTTOT_0 AS COST, ITMBPS.BPSNUM_0 AS VENDOR, BPSUPPLIER.BPSNAM_0 AS VENDNAME, ITMMASTER.TSICOD_2 AS CAT
FROM x3v11.PROD.ITMMASTER ITMMASTER
LEFT OUTER JOIN x3v11.PROD.ITMMVT ITMMVT ON ITMMASTER.ITMREF_0 = ITMMVT.ITMREF_0
LEFT OUTER JOIN x3v11.PROD.ITMFACILIT ITMFACILIT ON ITMMVT.ITMREF_0 = ITMFACILIT.ITMREF_0 AND ITMMVT.STOFCY_0 = ITMFACILIT.STOFCY_0
LEFT OUTER JOIN x3v11.PROD.ITMCOST ITMCOST ON ITMMVT.ITMREF_0 = ITMCOST.ITMREF_0 AND ITMMVT.STOFCY_0 = ITMCOST.STOFCY_0
LEFT OUTER JOIN x3v11.PROD.ITMBPS ITMBPS ON ITMMASTER.ITMREF_0 = ITMBPS.ITMREF_0
LEFT OUTER JOIN x3v11.PROD.BPSUPPLIER BPSUPPLIER ON ITMBPS.BPSNUM_0 = BPSUPPLIER.BPSNUM_0
WHERE ITMCOST.STOFCY_0 <> '115'
AND ITMFACILIT.MAXSTO_0 <> 0
AND ITMBPS.PIO_0 <> 99
AND ITMBPS.BPSNUM_0 LIKE CASE WHEN ? IS NOT NULL THEN ? ELSE '%' END
GROUP BY ITMMASTER.ITMREF_0, ITMMASTER.ITMDES1_0, ITMMASTER.ITMWEI_0, ITMCOST.CSTTOT_0, ITMBPS.BPSNUM_0, BPSUPPLIER.BPSNAM_0, ITMMASTER.TSICOD_2
ORDER BY ITMMASTER.ITMREF_0
I think you have specified the syntax for the subquery incorrectly:
INVQTY = (SELECT Sum(SINVOICED.QTY_0) AS INVQTY
FROM x3v11.PROD.SINVOICED SINVOICED
WHERE SINVOICED.INVDAT_0 BETWEEN
DATEADD(WEEK,-1,DATEADD(WEEK,DATEDIFF(WEEK,0,GETDATE()),0))
AND DATEADD(DAY,4,DATEADD(WEEK,-1,DATEADD(WEEK,DATEDIFF(WEEK,0,GETDATE()),0)))
AND SINVOICED.ITMREF_0 = ITMMASTER.ITMREF_0
),
I think it should be:
(SELECT Sum(SINVOICED.QTY_0)
FROM x3v11.PROD.SINVOICED SINVOICED
WHERE SINVOICED.INVDAT_0 BETWEEN
DATEADD(WEEK,-1,DATEADD(WEEK,DATEDIFF(WEEK,0,GETDATE()),0))
AND DATEADD(DAY,4,DATEADD(WEEK,-1,DATEADD(WEEK,DATEDIFF(WEEK,0,GETDATE()),0)))
AND SINVOICED.ITMREF_0 = ITMMASTER.ITMREF_0
) AS INVQTY,

Selecting Columns from another table inside a Select Query

It seems to be the query that I have created is a little bit messy.
Is there any other way to make it more readable?
Here's the query that I have created.
Select nullif((select count(*) from [casino_game].[dbo].[group_user] gu
where gu.group_id = (select pt.group_id from [casino_game].[dbo].[promo_trigger] pt
join [casino_game].[dbo].[promo_offer] po on po.trigger_id = pt.trigger_id
where pt.name = f.promo_name
group by pt.group_id)),0) as target_group, -- Number of customer uploaded to a free game program.
(cast(count(*) as decimal(11,2)) / nullif((select count(*) from [casino_game].[dbo].[group_user] gu
where gu.group_id = (select pt.group_id from [casino_game].[dbo].[promo_trigger] pt
join [casino_game].[dbo].[promo_offer] po on po.trigger_id = pt.trigger_id
where pt.name = f.promo_name
group by pt.group_id)), 0)) * 100 as claim_rate from [data].[dbo].[testgame]
This query is working, but I need some suggestion if there will be another way to make this working and more readable.
You can use OUTER APPLY to avoid using the same correlated sub-query twice
SELECT target_group,
( Cast(Count(*) AS DECIMAL(11, 2)) / NULLIF(target_group, 0) ) * 100 AS claim_rate
FROM [data].[dbo].[testgame]
OUTER apply (SELECT Count(*) AS target_group
FROM [casino_game].[dbo].[group_user] gu
WHERE gu.group_id = (SELECT pt.group_id
FROM
[casino_game].[dbo].[promo_trigger] pt
JOIN [casino_game].[dbo].[promo_offer]
po
ON po.trigger_id = pt.trigger_id
WHERE pt.NAME = f.promo_name
GROUP BY pt.group_id)) ou
I think the target table was group_user instead of testgame, and it must be a single row, no need for a join to many rows to testgame
select
COUNT(*) as target_group, -- Number of customer uploaded to a free game program.
-- It may cause the Divide by zero error if count(*) = 0
CASE WHEN COUNT(*) > 0 THEN (cast((SELECT COUNT(*) as value FROM [data].[dbo].[testgame]) as decimal(11,2)) / COUNT(*)) * 100 END as claim_rate
from
[casino_game].[dbo].[group_user] gu
inner join [casino_game].[dbo].[promo_trigger] pt on gu.group_id = pt.group_id
inner join [casino_game].[dbo].[promo_offer] po on po.trigger_id = pt.trigger_id

How to replace a NULL when a COUNT(*) returns NULL in DB2

I have a query:
SELECT A.AHSHMT AS SHIPMENT, A.AHVNAM AS VENDOR_NAME, D.UNITS_SHIPPED, D.ADPON AS PO, B.NUMBER_OF_CASES_ON_TRANSIT, C.NUMBER_OF_CASES_RECEIVED FROM AHASNF00 A
INNER JOIN (SELECT IDSHMT, COUNT(*) AS NUMBER_OF_CASES_ON_TRANSIT FROM IDCASE00 WHERE IDSTAT = '01' GROUP BY IDSHMT) B
ON (A.AHSHMT = B.IDSHMT)
LEFT JOIN (SELECT IDSHMT, (COUNT(*) AS NUMBER_OF_CASES_RECEIVED FROM IDCASE00 WHERE IDSTAT = '10' GROUP BY IDSHMT) C
ON (A.AHSHMT = C.IDSHMT)
INNER JOIN (SELECT ADSHMT, ADPON, SUM(ADUNSH) AS UNITS_SHIPPED FROM ADASNF00 GROUP BY ADSHMT, ADPON) D
ON (A.AHSHMT = D.ADSHMT)
WHERE A.AHSHMT = '540041134';
On the first JOIN statement I have a COUNT(*), on this count sometimes I will get NULL. I need to replace this with a "0-zero", I know think I know how to do it in SQL
ISNULL(COUNT(*), 0)
But this doesn't work for DB2, how can I accomplish this? All your help is really appreciate it.
Wrap a COALESCE around each of the nullable totals in your SELECT list:
SELECT A.AHSHMT AS SHIPMENT,
A.AHVNAM AS VENDOR_NAME,
COALESCE( D.UNITS_SHIPPED, 0 ) AS UNITS_SHIPPED,
D.ADPON AS PO,
COALESCE( B.NUMBER_OF_CASES_ON_TRANSIT, 0 ) AS NUMBER_OF_CASES_ON_TRANSIT,
COALESCE( C.NUMBER_OF_CASES_RECEIVED, 0 ) AS NUMBER_OF_CASES_RECEIVED
FROM ...
The inner joins you're using for expressions B and D mean that you will only receive rows from A that have one or more cases in transit (expression B) and have one or more POs in expression D. Is that the way you want your query to work?
Instead of using ISNULL(COUNT(*), 0),
try using COALESCE(COUNT(*),0)
use IFNULL(COUNT(*), 0) for DB2

Using JOINS in MySQL

I have this query which works perfectly:
SELECT *
FROM Customer
WHERE SacCode IN
(
SELECT SacCode
FROM SacCode
WHERE ResellerCorporateID = 392
ORDER BY SacCode
)
AND CustomerID IN
(
SELECT CxID
FROM CustAppointments
WHERE AppRoomID IN
(
SELECT AppRoomID
FROM ClinicRooms
WHERE ClinID IN
(
SELECT ClinID
FROM AppClinics
WHERE ClinDate >='20090101'
AND ClinDate <='20091119'
)
)
)
However, I need to see the value of ClinDate (inside the last nested query) so I've been told I need to rework the query using JOINS.
I have no idea how, can someone help please?
Thanks.
Here's a start:
SELECT *
FROM Customer c
INNER JOIN CustAppointments ca ON ca.CxId = c.CustomerID
INNER JOIN ClinicRooms cr ON cr.AppRoomID = ca.AppRoomID
INNER JOIN AppClinics ac ON ac.ClinID = cr.ClinID
WHERE ap.ClinDate BETWEEN '20090101' AND '20091119'
AND SacCode IN (SELECT sc.SacCode
FROM SacCode sc
WHERE sc.ResellerCorporateID = 392)
This will allow you to select columns from AppClinics.
Read this http://www.w3schools.com/Sql/sql_join.asp