SQL Server query to calculate balance account for suppliers - sql-server

I have 5 tables in my database
I want my SQL Server query can run like this:
But I don't know how can I get that, So Please help me.
Thanks.

select s.SupnName,
TotalPurchase = (select sum(p.Qntty * p.PurchsePrice)
from ProductsTble p
where p.supid = s.supid),
TotalPayement = (select sum(c.Cashvalue)
from CashMovementTbl c
where c.supid = s.supid)
from SuppliersTble s;
Make sure you have indexes ProductsTble(supid) and CashMovementTbl(supid)

Related

Joins and linked servers query causing delay

Hey guys the code below is taking a really long time. I've been looking at it for quite a while. Is there anything that stands out as the obvious cause of delay?
[SQLSRV-3-JB] is a linked server BTW
Select count(cast (Unique_ID as bigint)) as [Count],
T.[Region_Code],
T.[Region_Name],
U.[Region_Code],
Y.[Examination_Year],
case when [Subject] = 'MUSIC THEORY' THEN 'Theory'
else 'Practical'
end
from [SQLSRV-3-JB].[X].[dbo].[Exam_and_Candidate_Details] Y
left join [SQLSRV-3-JB].[X].[dbo].[UK_Exam_Centre_Info] T
on Y.Centre_Code = T.Centre_Code
left join [SQLSRV-3-JB].[X].[dbo].[UK_Exam_Centres] U
on Y.Centre_Code = U.Centre_Code
where Y.[Examination_Year] between 2010 and 2016
group by Y.[Examination_Year],
T.[Region_Code],
T.[Region_Name],
U.[Region_Code],
case when [Subject] = 'MUSIC THEORY' THEN 'Theory'
else 'Practical'
end
Yes, there is one very obvious problem - the remote server. When you use a linked server like this, SQL Server has a disturbing habit of pulling all of the data in the remote tables to the local server before performing JOINs or filtration.
The correct way to handle this is to make this query a view on the remote server, and query the view with your WHERE clause on your end. So, your remote code would look like this:
-- Remote Server
USE X
GO
CREATE VIEW dbo.ExamCenterInfo
AS
Select count(cast (Unique_ID as bigint)) as [Count],
T.[Region_Code],
T.[Region_Name],
U.[Region_Code],
Y.[Examination_Year],
case when [Subject] = 'MUSIC THEORY' THEN 'Theory'
else 'Practical'
end
from dbo.[Exam_and_Candidate_Details] Y
left join dbo.[UK_Exam_Centre_Info] T
on Y.Centre_Code = T.Centre_Code
left join dbo.[UK_Exam_Centres] U
on Y.Centre_Code = U.Centre_Code
group by Y.[Examination_Year],
T.[Region_Code],
T.[Region_Name],
U.[Region_Code],
case when [Subject] = 'MUSIC THEORY' THEN 'Theory'
else 'Practical'
end
Then your local code:
-- Local Server
SELECT *
FROM [SQLSRV-3-JB].[X].[dbo].ExamCenterInfo ECI
where ECI.[Examination_Year] between 2010 and 2016
NOTE: There is some possibility that this will pull all of the view output before filtering by year. If this is still a problem, you will have to create a more complex mechanism to execute the view with filtration on the remote server.

How to perform "select top 1 x from table" statement in spark sql

I am facing problem converting bellow query in spark-sql in pyspark
SQL-server query is
coalesce((Select top 1 f2.ChargeAmt from Fact_CMCharges f2
where f2.BldgID = f.BldgID
and f2.LeaseID = f.LeaseID
and f2.IncomeCat = f.IncomeCat
and f2.Period < f.Period
and f2.ActualProjected = 'Lease'
order by f2.Period desc),0) as Charge
I did not find replacing key word of top in pyspark sql . Kindly Help me
how could i convert this query in py-spark sql
Since you said Spark-SQL and if you have `DF', then you can use something like this.
df.limit(1).show()

Passing a SQL result to a 2nd SQL query

I'm coming to the end of setting up my first Python script which involves querying my SQL Server (which I've removed credentials for privacy reasons).
This is a excerpt of the code for which I can successfully login and query my SQL Server db.
I know my 2 SELECT queries work independently as I've tested already. But I've come unstuck setting the first SELECT query as a variable which I wish to pass into the 2nd Select queries where clause.
In SQL terms, I wish to set the adjusted date as the variable StartDate (from my first SELECT) and pass this to the Where statement in my 2nd SELECT statement. I think I'm failing on setting the variable properly. To reconfirm, I've verified the SELECT statements work from Python.
Is there something I need to add? Any suggestions appreciated.
import csv
import os
import urllib.request
import pymssql
conn = pymssql.connect(server='', user='', password='', database='')
StartDate = conn.cursor()
StartDate.execute('SELECT Dateadd(dd, -19, MAX(LastDateValue)) FROM tbl_Date')
ASXCodes = conn.cursor()
ASXCodes.execute('SELECT ASXCode FROM tbl_Company WHERE (ASX200 = 1 OR
MarketIndex =1 OR SegmentIndex = 1) AND Delisted = 0 AND LastTraded
>= StartDate ORDER BY ASXCode')
Just guessing - couldn't you do everything in one single query?
SELECT ASXCode FROM tbl_Company WHERE (ASX200 = 1 OR MarketIndex =1 OR SegmentIndex = 1) AND Delisted = 0 AND LastTraded >= (SELECT Dateadd(dd, -19, MAX(LastDateValue)) FROM tbl_Date) ORDER BY ASXCode
Also, I would imagine that tbl_Date.LastDateValue is indexed? If you get many records, that could be rather expensive...

Update on linked server with nested subquery

I want to update on a linked server the result of a query as well from a linked server.
The first sql snippet gives me the value to be updated:
SELECT mmdb_vessel.IMONo, mmdb_vessel.DeathDate
From OPENQUERY(MMDB, 'SELECT FunctionalLocation, IMONo, VesselStatus, CONVERT(VARCHAR(10), DeathDate, 102) AS DeathDate
FROM VESSEL
WHERE VESSEL.VesselStatusID <> 42 AND VESSEL.DeathDate is not null') as mmdb_vessel
, eb_all_v
WHERE
eb_all_v.IMO_No = mmdb_vessel.IMONo
AND eb_all_v.status = 'in service'
the second is actually what I'm not able to implement, it should show what I want to achieve:
UPDATE EPI2..EPI.PLANT
SET KIND_OF_LIQUIDATION_NO = 1
, LIQUIDATION_DATE = [result from snippet above].DeathDate
Where EPI2..EPI.PLANT.IMONo = [result from snippet above].IMONo
I'm not so sure if my explanation is sufficient, please feel free to ask for additional information!
Thanks, already in advance,
Werner
I would recommend to select the data from the remote server first and store the required data e.g. in a temptable, because LinkedServer and updates can have some sideeffects (e.g. performing a tablescan on the remote table, altough you would not expect it if an updaet is involved, etc) - but this depends on your exact usage/scenario.
Select data you need to update
SELECT * INTO #tmpTable FROM LINKEDSERVER.EPI.dbo.PLANT WHERE ....
Perform the update on local server
UPDATE EPI2..EPI.PLANT SET KIND_OF_LIQUIDATION_NO = 1, LIQUIDATION_DATE = t.DeathDate FROM #tmpTable t INNER JOIN EPI2..EPI.PLANT p on t.IMONo = p.IMONo

View from DB2 to SQL Server 2005

I'm attempting to move a view between DB2 and SQL Server.
CREATE VIEW msu.bad_bus_cnty_st_mstr
AS
SELECT id,
bus_cnty_cntry_cd,
bus_st,
bus_zip
FROM summit.mstr
WHERE ( bus_cnty_cntry_cd, bus_st ) IN (SELECT cnty_cntry_cd,
st
FROM uhelp.cnty_cntry_cd
WHERE
cnty_cntry_descr LIKE '%invalid%');
The view works in DB2, but doesn't work with SQL Server because of the WHERE clause. Can I have a recommendation on how to rewrite this view to work with SQL Server?
It usually helps to define what "doesn't work" means (e.g. what error did you get) and also to specify the version of SQL Server you are using.
Unfortunately SQL Server doesn't support IN() with more than one clause. However you can re-write your view this way:
ALTER VIEW msu.bad_bus_cnty_st_mstr
AS
SELECT id,
bus_cnty_cntry_cd,
bus_st,
bus_zip
FROM summit.mstr AS mstr
WHERE EXISTS
(
SELECT 1
FROM uhelp.cnty_cntry_cd
WHERE cnty_cntry_descr LIKE '%invalid%'
AND cnty_cntry_cd = mstr.bus_cnty_cntry_cd
AND st = mstr.bus_st
);
one way
CREATE VIEW msu.bad_bus_cnty_st_mstr
AS
SELECT id,
bus_cnty_cntry_cd,
bus_st,
bus_zip
FROM summit.mstr m
WHERE EXISTS( SELECT 1 FROM uhelp.cnty_cntry_cd c
WHERE c.cnty_cntry_descr LIKE '%invalid%'
AND c.bus_cnty_cntry_cd = m.bus_cnty_cntry_cd
AND c.st = m.bus_st)

Resources