I got such two queries:
SELECT
count (C.CaseDetailsId) as [Z telefonem]
,U.FirstName + ' ' + U.LastName as [Windykator]
from CaseDetails as C
join DebtorDetails as D on C.CaseDetailsId = D.CaseDetailsId
join Users as U on C.UserId = U.UserId
where D.DebtorDetailsId in
(SELECT DebtorDetailsId from DebtorPhone
where (IsValid = 'True') or (IsDefault = 'True'))
and C.CaseStatusId <> 2 and C.CaseStatusId <> 6 group by U.FirstName,U.LastName
e
and
SELECT
count (CaseDetailsId) as [Beztel]
,U.FirstName + ' ' + U.LastName as [Windykator]
from CaseDetails as C
join Users as U on C.UserId = U.UserId
where
C.CaseStatusId <> 2 and C.CaseStatusId <> 6 group by U.FirstName,U.LastName
I need to group the results of those two into 1 table so I suppose it would be best to connect them but I have no idea how to do it.
The query has to count rows in two cases
1) overall
2) where exists a specified row in another table
So in general -> I need to count number of cases (CaseDetailsId) for every employeer (Users) with and without phone number (DebtorPhones)
Below query will give you one record set from two queries using union. You can add insert statement above select to insert into your required table.
SELECT Count (C.casedetailsid) AS [Z telefonem],
U.firstname + ' ' + U.lastname AS [Windykator]
FROM casedetails AS C
JOIN debtordetails AS D
ON C.casedetailsid = D.casedetailsid
JOIN users AS U
ON C.userid = U.userid
WHERE D.debtordetailsid IN (SELECT debtordetailsid
FROM debtorphone
WHERE ( isvalid = 'True' )
OR ( isdefault = 'True' ))
AND C.casestatusid <> 2
AND C.casestatusid <> 6
GROUP BY U.firstname,
U.lastname
Union
SELECT Count (casedetailsid) AS [Z telefonem],
U.firstname + ' ' + U.lastname AS [Windykator]
FROM casedetails AS C
JOIN users AS U
ON C.userid = U.userid
WHERE C.casestatusid <> 2
AND C.casestatusid <> 6
GROUP BY U.firstname,
U.lastname
#Pratik Kaje not really. It shows 2 columns only - [Z tel] and [Windykator]
I tested a bit and ended with such query:
SELECT
[Windykator]
,[Beztel]
,[Z telefonem]
from
(SELECT
count (C.CaseDetailsId) as [Z telefonem]
,NULL as [Beztel]
,NULL as [Windykator]
from CaseDetails as C
join DebtorDetails as D on C.CaseDetailsId = D.CaseDetailsId
join Users as U on C.UserId = U.UserId
where D.DebtorDetailsId in
(SELECT DebtorDetailsId from DebtorPhone
where (IsValid = 'True') or (IsDefault = 'True'))
and C.CaseStatusId <> 2 and C.CaseStatusId <> 6
group by U.FirstName, U.LastName
UNION ALL
SELECT
NULL
,count (CaseDetailsId) as [Beztel]
,NULL
from CaseDetails as C
join Users as U on C.UserId = U.UserId
where
C.CaseStatusId <> 2 and C.CaseStatusId <> 6
group by U.FirstName, U.LastName
UNION ALL
SELECT
NULL
,NULL
,U.FirstName + ' ' + U.LastName
from CaseDetails as C
join Users as U on C.UserId = U.UserId
where
C.CaseStatusId <> 2 and C.CaseStatusId <> 6
group by U.FirstName, U.LastName
) as x
Almost perfectly however the results are not grouped. So it shows results with
NULLS NULLS [Bez tel]
NULLS [Z tel] NULLS
[Windykator] NULLS NULLS
Related
I have this query:
with users_having_connected as (
select u.id as user_id,
(a.connected_at is not null) has_connected
from core_user u
join core_profile p on u.id = p.user_id
join core_conversation c on (c.profile1_id = p.id or c.profile2_id = p.id)
join analytics_connection a on c.id = a.conversation_id
group by u.id, (a.connected_at is not null)
)
select u.id as user_id,
date_trunc('month', u.created at time zone 'UTC')::date as month,
p.community_id,
p.organization_id,
p.profile_type_intention,
(p.basic_account_completed and (p.is_mentor or p.is_entrepreneur)) as profile_is_completed,
exists(select 1 from core_message where core_message.sender_id = p.id) as has_sent_a_message,
(EXISTS (SELECT 1 FROM core_message WHERE core_message.receiver_id = p.id)) AS has_received_a_message,
(EXISTS (SELECT 1 FROM core_admin_conversation_w_resp WHERE core_admin_conversation_w_resp.initiator_id = p.id or core_admin_conversation_w_resp.responder_id = p.id)) AS has_one_by_one,
exists(select 1 from users_having_connected where user_id = u.id) as has_two_by_two
from core_user as u
join core_profile p on u.id = p.user_id
where
p.profile_type_intention is not null
Which worked fine until I added this line:
(EXISTS (SELECT 1 FROM core_admin_conversation_w_resp WHERE core_admin_conversation_w_resp.initiator_id = p.id or core_admin_conversation_w_resp.responder_id = p.id)) AS has_one_by_one,
This specific variable add causes this query to infinite loop. What do I need to do to fix it? Am I missing a set of parentheses somewhere?
I hope I can explain myself enough.
I'm working with JPA #Query. I need to do a Case-When.
If the id is from a certain company, return all employees, otherwise return only employees from that company
In PostgreSQL is working the query
SELECT * FROM VIEW_EMPLOYEE v
WHERE (v.name LIKE '%%' OR v.lastname LIKE '%%' OR v.sso LIKE '%%')
AND (CASE WHEN (SELECT c.acronym FROM company c WHERE id = 1) <> 'TH' THEN v.company_id = 1 ELSE TRUE END)
But when I code it in JPA #Query
#Query("SELECT u FROM ViewEmployee u WHERE (u.name LIKE %?1% OR u.lastname LIKE %?1% OR u.sso LIKE %?1%) " +
"AND (CASE WHEN (SELECT c.acronym FROM Company c WHERE c.id = ?2) <> 'TH' THEN u.viewEmployeeId.companyId = ?2 ELSE TRUE END)")
fun findEmployee(search: String, companyId: Long, pageable: Pageable): Page<ViewEmployee>
Give me this error message
unexpected token: = near line 1, column 251 [SELECT u FROM com.solucioneskuali.models.ViewEmployee u WHERE (u.name LIKE ?1 OR u.lastname LIKE ?1 OR u.sso LIKE ?1) AND (CASE WHEN (SELECT c.acronym FROM com.solucioneskuali.models.Company c WHERE c.id = ?2) <> 'TH' THEN u.viewEmployeeId.companyId = ?2 ELSE TRUE END)]
Can someone help to find what I'm doing wrong?
so I'm trying to build a view query but I keep failing using only joins so I ended up with this deformation.. Any tips on how I can write this query so I don't have to use 6 subselects?
The FeeSum and PaymentSum can be null, so ideally I do not want those in my result set and I also wouldn't like results where the FeeSum and the PaymentSum are equal.
Quick note: client is the table where the clients informations are stored (name, adress, etc..)
customer has a fk on client and is kind of a shell table for the client that store more information for the client,
payment is a list of all payments a customer did,
order is a list of all orders a customer did.
The goal is to get a list where we can track which customer has open fees to pay, based on the orders. It's a legacy project so don't ask why people can order before paying :)
SELECT
cu.Id as [CustomerId]
, CASE
WHEN cl.IsPerson = 1
THEN cl.[AdditionalName] + ' ' + cl.[Name]
ELSE cl.AdditionalName
END as [Name]
, cl.CustomerNumber
, (SELECT SUM(o.Fee) FROM [publication].[Order] o WHERE o.[State] = 2 AND o.CustomerId = cu.Id) as [FeeSum]
, (SELECT SUM(p.Amount) FROM [publication].[Payment] p WHERE p.CustomerId = cu.Id) as [PaymentSum]
, (SELECT MAX(o.OrderDate) FROM [publication].[Order] o WHERE o.[State] = 2 AND o.CustomerId = cu.Id) as [LastOrderDate]
, (SELECT MAX(p.PaymentDate) FROM [publication].[Payment] p WHERE p.CustomerId = cu.Id) as [LastPaymentDate]
, (SELECT MAX(f.Created) FROM [client].[File] f WHERE f.TemplateName = 'Reminder' AND f.ClientId = cl.Id) as [LastReminderDate]
, (SELECT MAX(f.Created) FROM [client].[File] f WHERE f.TemplateName = 'Warning' AND f.ClientId = cl.Id) as [LastWarningDate]
FROM
[publication].[Customer] cu
JOIN
[client].[Client] cl
ON cl.Id = cu.ClientId
WHERE
cu.[Type] = 0
Thanks in advance and I hope I didn't do anything wrong.
Kind regards
You could rewrite the correlated subqueries to instead use joins:
SELECT
cu.Id AS [CustomerId],
CASE WHEN cl.IsPerson = 1
THEN cl.[AdditionalName] + ' ' + cl.[Name]
ELSE cl.AdditionalName END AS [Name],
cl.CustomerNumber,
o.FeeSum,
p.PaymentSum,
o.LastOrderDate,
p.LastPaymentDate,
f.LastReminderDate,
f.LastWarningDate
FROM [publication].[Customer] cu
INNER JOIN [client].[Client] cl
ON cl.Id = cu.ClientId
INNER JOIN
(
SELECT CustomerId, SUM(Fee) AS [FeeSum], MAX(OrderDate) AS [LastOrderDate]
FROM [publication].[Order]
WHERE o.[State] = 2
GROUP BY CustomerId
) o
ON o.CustomerId = cu.Id
INNER JOIN
(
SELECT CustomerId, SUM(Amount) AS [PaymentSum], MAX(PaymentDate) AS [LastPaymentDate]
FROM [publication].[Payment]
WHERE o.[State] = 2
GROUP BY CustomerId
) p
ON p.CustomerId = cu.Id
INNER JOIN
(
SELECT ClientId,
MAX(CASE WHEN TemplateName = 'Reminder' THEN Created END) AS [LastReminderDate],
MAX(CASE WHEN TemplateName = 'Warning' THEN Created END) AS [LastWarningDate]
FROM [client].[File]
GROUP BY ClientId
) f
ON f.ClientId = cl.Id
WHERE
cu.[Type] = 0;
Simplified version of query below, but fundamental gist of it:
WITH ClientSpend AS
(
SELECT
c.ClientName
, CONVERT(INT, (ROUND(SUM(CASE WHEN e.Type = 1 THEN e.Dollars ELSE 0 END), 0))) AS 1_Dollars
, CONVERT(INT, (ROUND(SUM(CASE WHEN e.Type = 2 THEN e.Dollars ELSE 0 END), 0))) AS 2_Dollars
-- There's a bunch more of these for different 'Types'
FROM Expense e WITH(NOLOCK)
INNER JOIN Client c WITH(NOLOCK)
ON c.ClientID = e.ClientID
GROUP BY c.ClientName
)
SELECT
ClientName
, 1_Dollars
, 2_Dollars
FROM ClientSpend
GROUP BY ClientName
Type 2 has its own Expense table which breaks out into more granular detail that I need for a final CASE/SUM line in the CTE SELECT.
I tried testing the above query with a LEFT JOIN to this [ExpenseType2] table ON as many indexes as I can, and I noticed that the SUM on the 2_Dollars is higher when doing this. I'm assuming it's making multiple records even though I'm not selecting anything from the [ExpenseType2] table.
How do I prevent this?
Thanks,
Why not using a sub query? Or a simple select statement? Or you may need to assert more information with sample data.
SELECT first_name, 1_Dollars, 2_Dollars FROM
(
SELECT
c.ClientName
, CONVERT(INT, (ROUND(SUM(CASE WHEN e.Type = 1 THEN e.Dollars ELSE 0 END), 0))) AS 1_Dollars
, CONVERT(INT, (ROUND(SUM(CASE WHEN e.Type = 2 THEN e.Dollars ELSE 0 END), 0))) AS 2_Dollars
-- There's a bunch more of these for different 'Types'
FROM Expense e WITH(NOLOCK)
INNER JOIN Client c WITH(NOLOCK)
ON c.ClientID = e.ClientID
GROUP BY c.ClientName
) a
I wrote the following query to check duplicates.
select s.*,m.IsMember_Ind,
case when REPLACE(s.[ Owner Mobile],' ','')
in (select cd.Mobile
from Company_Detail cd
inner join MEMBERSHIP m
on cd.Company_ID = m.Company_ID
where m.IsMember_Ind = 1)
then 'Match'
else ' ' end as OwnerMobileMatch,
case when REPLACE(s.[ Contact Number],' ','')
in (select cd.Mobile
from Company_Detail cd
inner join MEMBERSHIP m
on cd.Company_ID = m.Company_ID
where m.IsMember_Ind = 1)
then 'Match' else ' ' end as ContactMobileMatch
from COMPANY c
inner join surreynonmembers s
on c.TTR_ID = s.[Company ID]
left outer join MEMBERSHIP m
on m.Company_ID = c.Company_ID
My problem is, the case statement returns as a match when finds an empty value which I do not need. How can I modify this query to return if there is only a value?
Have you tried this?
GO
SELECT s.*
,m.IsMember_Ind
,CASE
WHEN REPLACE(s.[ Owner Mobile], ' ', '') IN (
SELECT cd.Mobile
FROM Company_Detail cd
INNER JOIN MEMBERSHIP m ON cd.Company_ID = m.Company_ID
WHERE m.IsMember_Ind = 1
AND ISNULL(s.[ Owner Mobile], '') <> ''
)
THEN 'Match'
ELSE ' '
END AS OwnerMobileMatch
,CASE
WHEN REPLACE(s.[ Contact Number], ' ', '') IN (
SELECT cd.Mobile
FROM Company_Detail cd
INNER JOIN MEMBERSHIP m ON cd.Company_ID = m.Company_ID
WHERE m.IsMember_Ind = 1
AND ISNULL(s.[ Contact Number], '')<> ''
)
THEN 'Match'
ELSE ' '
END AS ContactMobileMatch
FROM COMPANY c
INNER JOIN surreynonmembers s ON c.TTR_ID = s.[Company ID]
LEFT JOIN MEMBERSHIP m ON m.Company_ID = c.Company_ID
GO