Sql Inner Join Dont Have Result - sql

First of all thanks a lot all replys and comments. I want to listed some fields from 4 tables. My question is if ODEMELER(Customer Payments) tables is dont have BORCLAR(Customers Debt) tables value. Namely;
MusteriID is = 1.
This Customer buy a item. I insert this process to BORCLAR table(BorcMusteriID=1) but ODEMELER table is null for this customer and OdemeMusteriID=!!! (null) because customer is not payment. And i want to list all of debts from all customers this code;
(SELECT SUM(BORCLAR.BorcTutari) FROM BORCLAR WHERE BORCLAR.BorcMusteriID=
ODEMELER.OdemeMusteriID)-
(SELECT SUM(ODEMELER.OdemeTutar) FROM ODEMELER where BORCLAR.BorcMusteriID=
ODEMELER.OdemeMusteriID))
AS [Borç Toplamı] FROM BORCLAR)
but this code is reply me only have BorcMusteriID,OdemeMusteriID valid records then my a lot of customers buy items but dont payment now. I dont list this. I try this code but it is wrong;
((SELECT SUM(BORCLAR.BorcTutari) FROM BORCLAR WHERE
BORCLAR.BorcMusteriID=ODEMELER.OdemeMusteriID)-
(SELECT SUM(ODEMELER.OdemeTutar) FROM ODEMELER where
BORCLAR.BorcMusteriID=
CASE (SELECT COUNT(*) FROM ODEMELER WHERE
ODEMELER.OdemeMusteriID=BORCLAR.BorcMusteriID)
WHEN 0 THEN ODEMELER.OdemeMusteriID = ODEMELER.OdemeMusteriID
ELSE ODEMELER.OdemeMusteriID=0 END)) AS [Borç Toplamı] FROM BORCLAR
Complete of my code;
set dateformat dmy
SELECT
(SELECT TOP 1 BORCLAR.BorcTarih FROM BORCLAR WHERE BORCLAR.BorcTarih <=
CONVERT(DATETIME, GETDATE(), 104)
and
BORCLAR.BorcMusteriID=MUSTERILER.MusteriID order by BORCLAR.BorcTarih desc)
as [TARİH],
MUSTERILER.Unvan,MUSTERILER.Ad + ' ' + MUSTERILER.Soyad AS [Adı Soyadı],
MUSTERILER.Mahalle +
' ' + MUSTERILER.Cadde + ' '+MUSTERILER.Sokak + ' ' + MUSTERILER.ApartmanAdi+
' NO:' +
MUSTERILER.Numara + ' KAT:' + MUSTERILER.Kat + ' DAİRE:'+
MUSTERILER.Daire AS [Adres],
ARACSUBETANIMLAR.AracSubeAdi as [Araç/Şube Adı],
((SELECT SUM(BORCLAR.BorcTutari) FROM BORCLAR WHERE BORCLAR.BorcMusteriID=
ODEMELER.OdemeMusteriID)-
(SELECT SUM(ODEMELER.OdemeTutar) FROM ODEMELER where BORCLAR.BorcMusteriID=
ODEMELER.OdemeMusteriID))
AS [Borç Toplamı] FROM BORCLAR
INNER JOIN ARACSUBETANIMLAR ON BORCLAR.BorcAracSube = ARACSUBETANIMLAR.AracSubeID
INNER JOIN ODEMELER ON BORCLAR.BorcMusteriID = ODEMELER.OdemeMusteriID
INNER JOIN MUSTERILER ON BORCLAR.BorcMusteriID = MUSTERILER.MusteriID
where
BORCLAR.BorcAracSube=ARACSUBETANIMLAR.AracSubeID
and
((SELECT SUM(BORCLAR.BorcTutari) FROM BORCLAR WHERE BORCLAR.BorcMusteriID=
ODEMELER.OdemeMusteriID)-
(SELECT SUM(ODEMELER.OdemeTutar) FROM ODEMELER where BORCLAR.BorcMusteriID=
ODEMELER.OdemeMusteriID)>0)
group by MUSTERILER.Unvan,MUSTERILER.Soyad,MUSTERILER.Ad,
ARACSUBETANIMLAR.AracSubeAdi,
ODEMELER.OdemeMusteriID,BORCLAR.BorcMusteriID,MUSTERILER.
Cadde,MUSTERILER.Daire,
MUSTERILER.ApartmanAdi,MUSTERILER.Mahalle,MUSTERILER.Kat,
MUSTERILER.Numara,MUSTERILER.Sokak,
MUSTERILER.MusteriID
Thanks a lot.

Looks like you want all customer balances regardless whether they have paid anything or not. You have purchases in one table (BORCLAR) and payments in the other table (ODEMELER). I am not sure what language you are speaking, but I guess "MusteriID" is the customer ID. You can use CTEs to get total purchases and payments by customer first and then join on that. Something like this:
;WITH BorclarTotal AS (
SELECT BORCLAR.BorcMusteriID, SUM(BORCLAR.BorcTutari) AS BorcTutari
FROM BORCLAR
GROUP BY BORCLAR.BorcMusteriID
), OdemelerTotal AS (
SELECT ODEMELER.OdemeMusteriID, SUM(ODEMELER.OdemeTutar) AS OdemeTutar
FROM ODEMELER
GROUP BY ODEMELER.OdemeMusteriID
)
SELECT bt.BorcMusteriID, bt.BorcTutari - ISNULL(ot.OdemeTutar, 0)
FROM BorclarTotal bt
LEFT JOIN OdemelerTotal ot ON bt.BorcMusteriID = ot.OdemeMusteriID
WHERE bt.BorcTutari != ISNULL(ot.OdemeTutar, 0);

Related

Not does not exclude query info

I have a really long query and I'm finding that my NOT is not excluding what's in parenthesis after the NOT.
I saw Exclude and where not exists, but I'd have to re-select for that, and there's too many complicatedly joined tables in what I selected already, plus one table is very big and takes a long time to select what I have already, so I can't re-select because it will make the query take too long. How do I get this exclusion to work?
INSERT INTO #UNeedingC(id, CASEID, firstname, lastname, userid, AGEOFNOTIFICATION, DATETIMEDECISIONMADE, DELEGATESYSTEM, Person_id, request_type_id, service_place_id, status_summary, externalUserId, subject, onDate, externalPersonId, externalSystemId)
select distinct
c.id
,uc.case_id
,t_case.FIRSTNAME as first
,t_case.LASTNAME as last
,t_case.user_id as userid
,CONVERT(VARCHAR, DATEDIFF(dd, SC.status_change_date, GETDATE())) + ' Day(s) ' + CONVERT(VARCHAR, DATEDIFF(hh, SC.status_change_date, GETDATE()) % 24) + ' Hour(s) ' as [AGE OF NOTIFICATION]
,SC.status_change_date AS [DATE TIME DECISION MADE]
,[ckoltp_sys].DBO.ckfn_GetStringLocaleValue(152,9,uc.delegate_system,50,0) AS [DELEGATESYSTEM]
,c.person_id
,uc.request_type_id ------
,uc.service_place_id
,uc.status_summary
,eou.external_id
,c.tzix_id+' '+[ckoltp_sys].dbo.ckfn_GetStringLocaleValue(148,9,uc.status_summary,5,0)+' type' AS subject
,dateadd( hour,41,dateadd(day,0,datediff(d,0,sc.status_change_date)) ) AS onDate
,emd.externalId externalPersonId
,eou.system_id as externalSystemId
--,u.disable
from
#tempC t_case with (NOLOCK)
inner join dbo.org_case c with (nolock) ON t_case.Person_id=c.Person_id
INNER JOIN dbo.org_2_case uc with (NOLOCK) ON uc.case_id=c.id
inner JOIN dbo.ORG_LOS S WITH (NOLOCK) ON S.case_id = UC.case_id
inner JOIN dbo.ORG_EXTENSION SC WITH (NOLOCK) ON SC.los_id= S.id
inner join dbo.org_user u with (NOLOCK) on u.id=t_case.user_id
inner join dbo.org_person op with (NOLOCK) on op.id=c.Person_id
inner JOIN dbo.u_person_concept_value MC ON MC.CID = op.cid --this is the slow table
inner join dbo.EXTERNAL_ORG_USER_DATA eou with (NOLOCK) ON eou.org_user_id = t_case.user_id
inner join dbo.EXTERNAL_person_DATA emd with (NOLOCK) ON emd.CID = op.cid --op.id --?
WHERE
DATEDIFF(day, SC.status_change_date , GETDATE()) <= 2
AND
u.disable <> 1
AND
( --(denied/approved)
dbo.ckfn_GetStringLocaleValue(148,9,uc.status_summary,5,0) = 'Denied'
OR
(dbo.ckfn_GetStringLocaleValue(148,9,uc.status_summary,5,0) in( 'Fully Approved', 'Partially Approved'))
)
AND
(
(
ISNULL(uc.request_type_id,'') in( 12)
AND DATEDIFF(month, SC.status_change_date , GETDATE()) <= 2
)
OR
(
ISNULL(uc.request_type_id,'') in( 10,11)
)
--OR
--(
-- --exclude this
-- (
-- MC.concept_id = '501620' --general val1 (1000/1001)
-- AND
-- (C.ID in (select case_id from #CASES where str_value in ('1000','1001'))
-- AND (uc.service_place_id = 31 OR uc.service_place_id = 32))
-- ) --not
--) --or
)--AND
AND
(t_case.firstname not like '%external%' and t_case.lastname not like '%case manager%')
AND
(
C.ID in (select case_id from #CASES where concept_id='501620')--MC.concept_id = '501620'
)
--overall around AND (denied/approved)--
and DBO.ckfn_GetStringLocaleValue(152,9,uc.delegate_system,50,0) in ('AP','CA')
AND NOT --this not is not working...this appears in query results
(
--exclude these
(
MC.concept_id = '501620'
AND
(C.ID in (select case_id from #CASES where str_value in ('1000','1001'))
AND (uc.service_place_id = 31 OR uc.service_place_id = 32))
) --not
) --
select * from #UNeedingC
results show what is excluded:
id caseid firstname lastname userid ageofNotification Datetimedecisionmade DelegateSys Person_id request_type_id service_place_id status_summary externalUserId subject
onDate externalPersonId externalSystemId
000256200 256200 Sree Par 1234 0 Apr 5 CA
4270000 11 31 3 sparee 000256200 Fully Approved tested Ad 2021-04-06 17:00 363000 2
My question: do you know why the NOT is not working and how I can get this to exclude without another select? See "this not is not working" comment. I searched online but only found exclude and where not exists, which require another select, which I don't want.
I think I figured it out: "NOT acts on one condition. To negate two or more conditions, repeat the NOT for each condition,"
from not on two things.
This seems to work:
...
AND
--exclude these
(
MC.concept_id = '501620' --general val1 (1000/1001)
AND
(C.ID not in (select case_id from #CASES where str_value in ('1000','1001'))
AND (uc.service_place_id not in ('31','32')))
) --not

Subquery returned more than 1 value - MS SQL

select Id,Prayaseeid, name,Gender,
(select name from tb_Category where id = Category) AS Category,
ideadescription,Domain,ProjectTerms,ProjectStartDate,Amountsanctioned,
(select Amount from tb_innovatorDisbursement where tbid ='TBINO1111A' and
applyingforcycle='1') AS AmountDisbursed,
projectstatus,projectoutcome
from tb_innovator
where tbid='TBINO1111A 'and applyingforcycle='1'
Use TOP to Limit rows to 1,
The Select queries in parenthesis resulting in more than one record
select Id,Prayaseeid, name,Gender,
(select TOP(1) name from tb_Category where id = Category) AS Category,
ideadescription,Domain,ProjectTerms,ProjectStartDate,Amountsanctioned,
(select TOP(1) Amount
from tb_innovatorDisbursement where tbid ='TBINO1111A' and applyingforcycle='1') AS AmountDisbursed,
projectstatus,projectoutcome from tb_innovator
where tbid='TBINO1111A 'and applyingforcycle='1'
You need to test your sub queries for the where clause to make sure the values you are searching do not have multiple records. I would use (Top 1 ) for any column other than the Id column assuming the Id column must be unique as the name suggests.
Update query
select ti.Id,
ti.Prayaseeid,
ti.name,
ti.Gender,
(select TOP(1) name from tb_Category where id = ti.Category) AS Category,
ti.ideadescription,
ti.Domain,
ti.ProjectTerms,
ti.ProjectStartDate,
ti.Amountsanctioned,
tid.Amount AS AmountDisbursed,
ti.projectstatus,
ti.projectoutcome
from tb_innovator ti
INNER JOIN tb_innovatorDisbursement tid ON tid.Tbid = ti.tbid
AND tid.applyingforcycle='1'
where ti.tbid='TBINO1111A 'and ti.applyingforcycle='1'
Perhaps you should use JOIN:
select i.Id, i.Prayaseeid, i.name, i.Gender, c.Category,
i.ideadescription, i.Domain, i.ProjectTerms, i.ProjectStartDate, i.Amountsanctioned,
id.Amount from tb_innovatorDisbursement
i.projectstatus, i.projectoutcome
from tb_innovator i left join
tb_Category c
on i.category = c.id left join
tb_innovatorDisbursement id
on id.tbid = i.dbid and id.applyingforcycle = '1'
where i.tbid = 'TBINO1111A 'and i.applyingforcycle = '1';
Note that all column names are qualified as well, indicating what table they come from.

Sql Joining 3 Tables Query for Loan Total Result

I have to get the total of Customer Loan from 3 tables the two tables are given loan to sum and the other subtract the paid amount and the tables have Customer ID in common. so far I can get the result only if the Customer ID exist in all tables but if it doesn't exist in one table I won't get Customer in my result. or I get NULL customer IDs when I anchor to the customer.
SELECT
AS1.C_ID AS [Customer ID],
ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
(ISNULL(AS1.OldCustomerLoan, 0) +
ISNULL(AS2.NewGivenLoan, 0) -
ISNULL(AS3.LoanPaid,0) ) AS Total
FROM
Customer C
LEFT OUTER JOIN
(SELECT
MOC.C_ID,
SUM(MOC.Quantity) AS OldCustomerLoan
FROM
Money_On_Customer MOC (NOLOCK)
GROUP BY
MOC.C_ID) AS1
ON c.C_Id = AS1.C_Id
LEFT OUTER JOIN
(SELECT
NGL.C_ID
,SUM(NGL.G_Take_Loan) AS NewGivenLoan
FROM
Given_Loan NGL
GROUP BY
NGL.C_ID) AS2
ON c.C_Id = AS2.C_Id
LEFT OUTER JOIN
(SELECT
GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid
FROM
Given_Loan_Paid GLP
GROUP BY
GLP.C_ID ) AS3
ON c.C_Id = AS3.C_Id
Here Is a picture of my two results:
When I get NULL Customer IDs
When I don't get All the Customers
You need to use c.c_id for the first column
In order to only get records where they exist in at least one of the tables you can add this to you query, just put you current query in place of the dots, and add the leftid col
Select *
From
(Select c.c_id custonerid,
Coalesce(Coalesce(as1.c_id,as2.c_id),as3.c_id) leftid,......
From ....
) ilv
Where leftid is not null
You might be able to just add
Where coalesce(coalesce(as1.c_id,as2.c_id),as3.c_id) is not null
To then end of your query
#Ab Bennett's answer is right,
because you should use your main(master) table's primary key column
if Customer ID is not available in as1 (Money_On_Customer) it will show null.
Hope you understand my explanation.
UPDATE:
and use following for getting customer id
COALESCE(c.C_Id, AS1.C_Id, AS2.C_Id)
you will get first not null Customer ID
Here is My answer with the help of #Ab Bennett
Select *
From
(
SELECT
C.C_Name AS [Customer ID],
ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
(ISNULL(AS1.OldCustomerLoan, 0) +
ISNULL(AS2.NewGivenLoan, 0) -
ISNULL(AS3.LoanPaid,0) ) AS Total
FROM
Customer C
LEFT OUTER JOIN
(SELECT
MOC.C_ID,
SUM(MOC.Quantity) AS OldCustomerLoan
FROM
Money_On_Customer MOC (NOLOCK)
GROUP BY
MOC.C_ID) AS1
ON c.C_Id = AS1.C_Id
LEFT OUTER JOIN
(SELECT
NGL.C_ID
,SUM(NGL.G_Take_Loan) AS NewGivenLoan
FROM
Given_Loan NGL
GROUP BY
NGL.C_ID) AS2
ON c.C_Id = AS2.C_Id
LEFT OUTER JOIN
(SELECT
GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid
FROM
Given_Loan_Paid GLP
GROUP BY
GLP.C_ID ) AS3
ON c.C_Id = AS3.C_Id) ilv
Where not ([Old Loan] = 0 and [New Given Loan]=0 and PaidLoanAmount =0 )

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 do I display different values as different columns in SQL?

I have a table with columns UserID, SiteID, SiteViews and another with UserID, First, Last
And I need to display the data as First + Last, Site1Views, Site2Views
There are only 2 site IDs and I need to have the sum of the SiteViews per User.
Currently I have:
select s.UserFirstName + ' ' + s.UserLastName as 'Name',
j1.SiteViews as 'Site1Name',
j2.SiteViews as 'Site2Name'
from (Users s INNER JOIN Usage j on s.UserID = j.UserID)
I don't know how to do this. Any help would be appreciated.
Sounds like you might want to use PIVOT for this? I can't test it, but this should get you going int he right direction?
select s.UserFirstName + ' ' + s.UserLastName as Name,
[Site1Name],
[Site2Name]
FROM
(SELECT s.UserFirstName + ' ' + s.UserLastName,
SiteName,
SiteVisits
from Users s
INNER JOIN Usage j1
on s.UserID = j1.UserID
)
PIVOT (SUM(SiteVisits) FOR SiteName IN ([Site1Name],[Site2Name])) as p
how I understood it
select s.UserFirstName + ' ' + s.UserLastName as Name
,(Select COUNT(*) from SiteViews s1 where s.UserID = s1.UserID /*other condition*/) as SiteView1
,(Select COUNT(*) from SiteViews s2 where s.UserID = s2.UserID /*other condition*/) as SiteView2
from Users s