How to SUM a column value in MSSQL - sql-server

I am new to mssql ,Here I need to SUM a column values.
But in my case have some joins between the tables finally I have a column with 2 rows of output .
What I want to do is I want to SUM the final output of my query.
This is my query :
SELECT
SUM(ESCD.ITEM_QTY) * ((SELECT COLOC_PROD_PRICE
FROM LOM_LNK_PROD_COMP
WHERE COLOC_PROD_CODE = ITEM_ID)
/
((SELECT LMUL.UOL_CONV_QTY
FROM LOM_MST_UOM_LINK AS LMUL
JOIN LOM_MST_PRODUCT AS LMP
ON LMUL.UOL_MAIN_UOM_CODE = LMP.PROD_STOCK_UOM
AND LMP.PROD_CODE = ESCD.ITEM_ID)/LMUL.UOL_CONV_QTY )) AS 'TOTAL_AMOUNT'
FROM EC_SHOPPING_CART_DETAIL AS ESCD
JOIN LOM_MST_UOM_LINK AS LMUL
ON LMUL.UOL_MAIN_UOM_CODE = ITEM_PACK_SIZE
WHERE CREATED_BY = 'xyz'
AND CHECK_OUT = 'FALSE'
GROUP BY ITEM_ID,LMUL.UOL_CONV_QTY
Output :
Expected AS :
can anyone help me to solve this .

Try the following:
SELECT
SUM(X.TOTAL_AMOUNT) AS 'TOTAL_AMOUNT'
FROM
(
SELECT
SUM(ESCD.ITEM_QTY) * ((SELECT COLOC_PROD_PRICE
FROM LOM_LNK_PROD_COMP
WHERE COLOC_PROD_CODE = ITEM_ID)
/
((SELECT LMUL.UOL_CONV_QTY
FROM LOM_MST_UOM_LINK AS LMUL
JOIN LOM_MST_PRODUCT AS LMP
ON LMUL.UOL_MAIN_UOM_CODE = LMP.PROD_STOCK_UOM
AND LMP.PROD_CODE = ESCD.ITEM_ID)/LMUL.UOL_CONV_QTY )) AS 'TOTAL_AMOUNT'
FROM EC_SHOPPING_CART_DETAIL AS ESCD
JOIN LOM_MST_UOM_LINK AS LMUL
ON LMUL.UOL_MAIN_UOM_CODE = ITEM_PACK_SIZE
WHERE CREATED_BY = 'xyz'
AND CHECK_OUT = 'FALSE'
GROUP BY ITEM_ID,LMUL.UOL_CONV_QTY
) X;

Related

How will SQL Server execute this WITH clause

I have the following query. Here 'B' is giving me non repeated MessageIds and i am using them in subquery with A, B is internally using A.
So when i call SELECT in the last part, will it execute A again or will it use data already fetched while B was being called ?
WITH A as (
SELECT z.Name, ze.Inside, ze.MessageId, ze.DateTime
FROM ZoneStateEntries ze
INNER JOIN Zone z
ON ze.ZoneId = z.ZoneId
WHERE ze.ObjectId = 1324
AND (Inside = 1 OR Inside = 0)
AND ze.DateTime BETWEEN '2018-10-22 00:00:00' AND '2019-11-05 00:00:00'
),
B as (
SELECT a.MessageId
FROM A a
INNER JOIN A b
on a.MessageId = b.MessageId
GROUP BY a.MessageId
HAVING COUNT(a.MessageId) = 1
)
SELECT *
FROM A
WHERE MessageId IN (
SELECT *
FROM B
)
AND a.Inside = 1
ORDER BY DateTime DESC
The data here is huge and we can't afford to execute query A multiple times. Can we optimize it further?
A a INNER JOIN A b looks like unnecessary. You can use COUNT(DISTINCT MessageId) for getting unique messages.
WITH A as (
SELECT z.Name, ze.Inside, ze.MessageId, ze.DateTime
FROM ZoneStateEntries ze
INNER JOIN Zone z
ON ze.ZoneId = z.ZoneId
WHERE ze.ObjectId = 1324
AND (Inside = 1 OR Inside = 0)
AND ze.DateTime BETWEEN '2018-10-22 00:00:00' AND '2019-11-05 00:00:00'
)
SELECT *
FROM A
WHERE MessageId IN (
SELECT MessageId
FROM A
GROUP BY MessageId
HAVING COUNT(DISTINCT MessageId) = 1
)
AND a.Inside = 1
ORDER BY DateTime DESC

SQL Server : calculated column for parent/child level

Having some issues displaying a calculated column.
I'm displaying a line for parent, then a few (anywhere between 1-5) lines for each child item.
My first query is this:
Select
_r1 = pbhier.r1
, pb.parent_id
, pb.Product_id
, pb.LastCost
, pb.AverageCost
, pb.FirstDatePurchased
, lrd.LastReceivingDate
, inv_units = isnull(inv.quantity,0)
, sales_units = convert(int,isnull(sales.SalesUnits,0))
, number_months_supply = case when isnull(sales.salesUnits,0) = 0 then isnull(inv.quantity,0)
else
case when (isnull(sales.salesUnits,0)/12) = 0 then 0
else
(convert(int,(inv.quantity/(isnull(sales.salesUnits,0)/12)))) end end
, inv.quantity, sales.SalesUnits
, ext_AverageCost = isnull(inv.quantity,0) * pb.averagecost
INTO #tempdata
From Products pb
inner join #TempFinalHier pbhier on pb.product_id = pbhier.product_id
left join #inventoryPC inv (nolock) on pb.product_id = inv.product_id
left join #tempTotSalesPC sales (nolock) on pb.product_id = sales.product_id
left join #lastReceivingDate lrd on lrd.rm_product_id = pb.product_id
where pb.Parent_ID in (select parent_id from #FinalParentSelection)
This creates a temp data set. The column "number_months_supply" does not need to be calculated above but the same formula should be used in my final query. My final query below gets me the final result set:
Select distinct
H.R1 , H.R2, H.Lvl,
case
when R1 <> R2
then H.parent_sku
else H.SKU
end as SKU,
H.parent_sku,
FirstReceiptDate = min(B.FirstDatePurchased),
LastReceiptDate = max(B.LastReceivingDate),
OnHand = sum(B.inv_units),
SalesUnits = sum(B.sales_units),
case
when isnull(sum(B.sales_units),0) = 0
then isnull(sum(B.inv_units),0)
else
case
when (isnull(sum(B.sales_units),0)/12) = 0
then 0
else convert(decimal(10, 2), (sum(B.inv_units) / (isnull(sum(B.sales_units), 0) / 12)))
end
end,
max(B.ext_AverageCost) as ext_AverageCost
From
#TempFinalHier H
join
#TempData1 B on (B._R1 between H.R1 and H.R2)
-- where H.Lvl=1 --Show only parent line
Group By
H.R1, H.R2, H.Lvl, H.parent_sku
having
sum(B.number_months_supply) > 12 --#MonthsSupplyGreaterThanOrEqual
Order by
R1
What I'm trying to get is:
'onHand' for parent line (lvl1) needs to be sum of all child rows (lvl2). same applies to 'SalesUnits'. Finally, Number_months_supply formula is (inv/sales_units)*12. I would like to display the number_months_supply as numeric with 2 decimal points.
Would appreciate some help with this.
Thanks.

SQL server 2012 - Query on retrieving matching records from a table by cross checking with two other tables

I have three tables (say A,B and C) with same column names and datatype. And these tables can be joined using four unique columns, say name,company,Seq_Number and role. Now I want to select records of particular role from table A and cross check them with the records in Table B and C.If they do not exist in both the tables, then we need to deactivate/remove those records from Table A. The problem is, the records which does not exist in table B might exist in Table C. So, I need to remove the records of particular role only if they don't exist in both B & C tables. I tried with the below query. But it is not returning the expected result. Kindly help me on this
SELECT DISTINCT FAT_Cust.name
, FAT_Cust.Company
, FAT_Cust.role
, FAT_Cust.Seq_Number
, Cust.name
, Cus.Company
, Cust.role
, Cust.Seq_Numberfrom (
SELECT DISTINCT ALC.NAME, ALC.Company, ALC.ROLE, ALC.Seq_Number
FROM AL_Customer ALC
INNER JOIN BL_Customer LPC ON ALC.NAME = LPC.NAME
AND ALC.Company = LPC.Company
AND ALC.ROLE = LPC.ROLE
AND ALC.Seq_Number = LPC.Seq_Number
AND ALC.Record_Active = 1
UNION SELECT DISTINCT ALC.NAME, ALC.Company, ALC.ROLE, ALC.Seq_Number
FROM AL_Customer ALC
INNER JOIN CL_Customer CLC ON ALC.NAME = CLC.NAME
AND ALC.Company = CLC.Company
AND ALC.ROLE = CLC.ROLE AND ALC.Seq_Number = CLC.Seq_Number
AND ALC.Record_Active = 1
) Cust
RIGHT OUTER JOIN AL_Customer FAT_Cust ON FAT_Cust.NAME = Cust.NAME
AND FAT_Cust.Company = Cust.Company
AND FAT_Cust.ROLE = Cust.ROLE
AND FAT_Cust.Seq_Number = Cust.Seq_Number
AND FAT_Cust.Record_Active = 1
WHERE Cust.NAME IS NULL
AND Cust.Company IS NULL
AND Cust.ROLE IS NULL
AND Cust.Seq_Number IS NULL
AND Cust.ROLE < > 'OWN'
Please try the query given below
SELECT ALC.* FROM AL_Customer ALC
LEFT JOIN BL_Customer BPC ON ALC.NAME = BPC.NAME
AND ALC.Company = BPC.Company
AND ALC.ROLE = BPC.ROLE
AND ALC.Seq_Number = BPC.Seq_Number
AND ALC.Record_Active = 1
AND BLC.Record_Active = 1
LEFT JOIN CL_Customer CPC ON ALC.NAME = CPC.NAME
AND ALC.Company = CPC.Company
AND ALC.ROLE = CPC.ROLE
AND ALC.Seq_Number = CPC.Seq_Number
AND ALC.Record_Active = 1
AND CLC.Record_Active = 1
WHERE ALC.Record_Active = 1
AND (BPC.NAME IS NULL)
AND (CPC.NAME IS NULL)
you can add more condition is where class to narrow down the matching criteria. the above query is assuming that name is present for all the records in the table. I hope this will resolve your issue.

Need to extract only the one row using join query

I am trying to extract one record from joining the Table X and Table Y.
Below is the query am using
SELECT (select ACCOUNTSALESFORCEDETAILID
FROM sysdba.ACCOUNTSALESFORCEDETAIL AS a1
WHERE ORGSALESFORCEID = 'QWKHAA000STK'
AND ACCOUNTID = O.ACCOUNTID
and MODIFYDATE = (
SELECT MIN(MODIFYDATE) AS MODIFYDATE
FROM sysdba.ACCOUNTSALESFORCEDETAIL
WHERE ACCOUNTID = a1.ACCOUNTID
AND ORGSALESFORCEID = a1.ORGSALESFORCEID
GROUP BY ACCOUNTID, ORGSALESFORCEID
)
),
a.ORGSALESFORCEID
FROM sysdba.ACCOUNTSALESFORCEDETAIL a
JOIN sysdba.ACCOUNT O on a.ACCOUNTID=O.ACCOUNTID
WHERE O.ACCOUNTID ='A61E6C43EE71'
AND A.ORGSALESFORCEID in ('QWKHAA000STK','QWKHAA01KXNC','QWKHAA01KXNE')
Below s the result am getting now:
ACCOUNTSALESFORCEID ORGSALESFORCEID
QB46AC89800B QWKHAA000STK
QB46AC89800B QWKHAA01KXNC
QB46AC89800B QWKHAA01KXNE
But i need only First row as the output..
Please help.
Have a try like this
SELECT TOP(1) col1,ORGSALESFORCEID
FROM
(SELECT
(
SELECT
ACCOUNTSALESFORCEDETAILID
FROM
sysdba.ACCOUNTSALESFORCEDETAIL AS a1
WHERE (ORGSALESFORCEID = 'QWKHAA000STK')
AND (ACCOUNTID=O.ACCOUNTID)
AND (MODIFYDATE =( SELECT MIN(MODIFYDATE) AS MODIFYDATE
FROM sysdba.ACCOUNTSALESFORCEDETAIL
WHERE (ACCOUNTID = a1.ACCOUNTID) AND (ORGSALESFORCEID=a1.ORGSALESFORCEID)
GROUP BY ACCOUNTID, ORGSALESFORCEID)
)
) AS col1
,a.ORGSALESFORCEID
FROM
sysdba.ACCOUNTSALESFORCEDETAIL a JOIN sysdba.ACCOUNT O on a.ACCOUNTID=O.ACCOUNTID
WHERE O.ACCOUNTID='A61E6C43EE71' and A.ORGSALESFORCEID in ('QWKHAA000STK','QWKHAA01KXNC','QWKHAA01KXNE')
) AS temp

how to convert the below subquery into joins using one update statement

Below is a complete query I have and the ultimate aim is to update the claim table. But it should be only one statement without any subquery, only joins are allowed because I am going to run this in an appliance which won't support subquery:
DECLARE #DecWdrwn as TABLE(CtryId smallint, CmId int, DecWdrwnDt int);
WITH s AS
(
SELECT
Ctryid,CmId,Dt,
ISNULL((
SELECT max(CmHistDtTmId)
FROM ClaimHistory l
WHERE St = 3
AND l.Ctryid = c.Ctryid
AND l.CmId = c.CmId)
, 0) MaxDec,
ISNULL((
SELECT max(CmHistDtTmId)
FROM ClaimHistory l
WHERE St = 7
AND l.Ctryid = c.Ctryid
AND l.CmId = c.CmId)
, 0) MaxSet
FROM
ClaimHistory c
WHERE
St =3
)
INSERT INTO #DecWdrwn
SELECT CtryId, CmId, Max(Dt) DecDt
FROM s
WHERE MaxSet > MaxDec
GROUP BY CtryId,CmId
Your response is much appreciated...
UPDATE Claims
SET CmDclnWdwnDt = (
SELECT DecWdrwnDt
FROM #DecWdrwn d
WHERE d.CmId = Claims.CmId
AND d.CtryId = Claims.CtryId
)
WHERE EXISTS (
SELECT *
FROM #DecWdrwn d
WHERE d.CmId = Claims.CmId
AND d.CtryId = Claims.CtryId
)
Please try INNER JOIN Update:
UPDATE a
SET a.CmDclnWdwnDt = b.DecWdrwnDt
FROM Claims a, #DecWdrwn b
WHERE a.CmId = b.CmId AND
a.CtryId =b.CtryId

Resources