SQL Counting Records with Count and Having - sql

I'm having problems with what I thought was a simple query to count records:
SELECT req_ownerid, count(req_status_lender) AS total6
FROM bor_requests
WHERE (req_status_lender = 0 AND req_status_borrower = 0) OR
(req_status_lender = 1 AND req_status_borrower = 1)
GROUP BY req_ownerid
HAVING req_ownerid = 70
I thought this would count all the records where (req_status_lender = 0 AND req_status_borrower = 0) and (req_status_lender = 1 AND req_status_borrower = 1) and then give me the total but it only gives me the total for either (req_status_lender = 0 AND req_status_borrower = 0) or (req_status_lender = 1 AND req_status_borrower = 1).
Any ideas what I'm doing wrong?

You should use the HAVING clause only to limit on something that's been aggregated in your query above - e.g. if you want to select all those rows where a SUM(....) or COUNT(...) is larger than say 5, then you'd use HAVING SUM(...) > 5
What you're doing here is a standard WHERE clause - add it there!
SELECT req_ownerid, count(req_status_lender) AS total6
FROM bor_requests
WHERE req_ownerid = 70
AND ((req_status_lender = 0 AND req_status_borrower = 0) OR
(req_status_lender = 1 AND req_status_borrower = 1))
GROUP BY req_ownerid

Related

How to Update with subquery in PostgreSQL

I have a function in MS SQL Server just like this:
UPDATE r
SET
monthly =
(
SELECT SUM(-h.value_ini - h.purchase + h.sold + h.value_fin)
FROM hist_portfolio AS h
WHERE h.comp_id = r.comp_id
AND h.port_id = r.port_id
AND h.exte_id = r.cate_id
AND h.type_id = #type_rel_aux
AND h.hcar_day > #date_month_before
AND h.hcar_day <= #date_base
)
FROM #Month_Table r
WHERE type = 1;
and thats the result (after update):
Seq monthly
2 102471,34
1 -5129,46
3 -29841,23
4 0
But when I execute the same update in a fuction in PostgreSQL, all the rows get the same value:
UPDATE Month_Table
SET variacao_mes_rs = (
SELECT SUM(-h.value_ini - h.purchase + h.sold + h.value_fin)
FROM hist_portfolio AS h
WHERE h.comp_id = r.comp_id
AND h.port_id = r.port_id
AND h.exte_id = r.cate_id
AND h.type_id = v_type_rel_aux
AND h.hcar_day > v_date_month_before
AND h.hcar_day <= v_date_base) FROM Month_Table r WHERE type = 1;
Result (after update), all the same value of Seq 3:]
Seq monthly
1 -29841,23
2 -29841,23
3 -29841,23
4 -29841,23
I don't see the cause of the problem...
Does PostgreSQL have different rules on UPDATE?
Can anyone help me?
Remove the FROM clause from Postgres:
UPDATE Month_Table r
SET variacao_mes_rs = (
SELECT SUM(-h.value_ini - h.purchase + h.sold + h.value_fin)
FROM hist_portfolio AS h
WHERE h.comp_id = r.comp_id
AND h.port_id = r.port_id
AND h.exte_id = r.cate_id
AND h.type_id = v_type_rel_aux
AND h.hcar_day > v_date_month_before
AND h.hcar_day <= v_date_base)
WHERE type = 1;
The FROM clause in an UPDATE behaves differently in the two databases, as you have discovered.

CASE WHEN THEN Cannot perform an aggregate function on an expression containing an aggregate or a subquery

this is my code:
SELECT SUM
(CASE
WHEN (dbo.EMBARQUE.EmbEst) = 0 THEN
0
WHEN (dbo.EMBARQUE.EmbEst) = 3 THEN
0
WHEN (dbo.EMBARQUE.EmbEst) = 6 THEN
0
WHEN (dbo.EMBARQUE.EmbEst) = 7 THEN
CASE
WHEN (SELECT COUNT (dbo.CUMPLIDO.CumpCod) from dbo.CUMPLIDO where dbo.CUMPLIDO.EmbCod = dbo.EMBARQUE.EmbCod and dbo.CUMPLIDO.CumpVol = 0) > 0 THEN
0
ELSE
dbo.EMBARQUE.EmbVol
END
ELSE
dbo.EMBARQUE.EmbVol
END) FROM dbo.EMBARQUE
You have a subquery inside sum(). That isn't allowed. This version uses a subquery to calculate the flag you want and then moves the filtering logic to the WHERE clause:
SELECT SUM(e.EmbVol)
FROM (SELECT e.*,
(CASE WHEN EXISTS (SELECT 1 FROM dbo.CUMPLIDO c WHERE c.EmbCod = e.EmbCod AND c.CumpVol = 0)
THEN 1 ELSE 0
END) as is_CumpVol_0
FROM dbo.EMBARQUE e
WHERE e.EmbEst NOT IN (0, 3, 6)
) e
WHERE e.EmbEst <> 7 OR is_CumpVol_0 = 0;

sql how to add inner join and multiple conditions to filter

I have this query
SELECT DISTINCT IP.IRId
FROM cmp.NPTable NP
INNER JOIN IPTable IP ON IP.IPtId = NP.IPd
LEFT JOIN IPCTable IPC ON IPC.IPId = NP.IPId
WHERE NP.PCN Id = #PCNId
AND (IP.IsCompliant = 1 AND IPC.CheckId = 1) OR (IP.IsCompliant = 0 AND IPC.CheckId = 1)
This is not working correcty
THe IPTable either has IsCompliant = null, 0 or 1 -- this is basically to indicate true or false
IPC.CheckId is either 1 or 2 -- this is the primary ID in this table
The only match integer match is the value 1 between the two tables.
I only want to bring back rows if IsCompliant = 1 and CheckId = 1
else if IsCompliant is null or 0, then CheckId = 2.
The clause I added to my where which is
AND (IP.IsCompliant = 1 AND IPC.CheckId = 1) OR (IP.IsCompliant = 0 AND IPC.CheckId = 1)
This does not work. Help. Will be very appreciated.
Thanks
WHERE NP.PCN Id = #PCNId
AND
(
(IP.IsCompliant = 1 AND IPC.CheckId = 1) OR
((IP.IsCompliant is null or IP.IsCompliant = 0) AND IPC.CheckId = 2)
)

SQL - WHERE with CASE statement

SELECT TOP 1
CostValue
FROM
[~client_table~].[dbo].[CostRules] AS CostRule
WHERE
(CASE
WHEN DATALENGTH(CostRule.ModelName) = 0
THEN
CostRule.Type = 1
AND CostRule.Manufacturer = Printer.ManufacturerId
AND CostRule.ColorType = 1
ELSE
CostRule.Type = 2
AND CostRule.ModelName = Printer.ModelName
AND CostRule.ColorType = 1
END
)
) AS MonoCost
I want to define my where statement depending on the datalength of CostRule.ModelName. But i got an error: Incorrect syntax near '='. in CostRule.Type = 1 and i got a error in the ELSE statement.
Must be like this:
...
WHERE
(DATALENGTH(CostRule.ModelName) = 0
AND CostRule.Type = 1
AND CostRule.Manufacturer = Printer.ManufacturerId
AND CostRule.ColorType = 1)
OR
(DATALENGTH(CostRule.ModelName) != 0
AND CostRule.Type = 2
AND CostRule.ModelName = Printer.ModelName
AND CostRule.ColorType = 1)
The CASE-style from your query cannot work.
you can change your statement like this:
SELECT TOP 1
CostValue
FROM
[~client_table~].[dbo].[CostRules] AS CostRule
WHERE CostRule.ColorType=1
AND CostRule.Type=CASE WHEN DATALENGTH(CostRule.ModelName) = 0 THEN 1 ELSE 2 END
AND CostRule.Manufacturer=CASE WHEN DATALENGTH(CostRule.ModelName) = 0 THEN Printer.ManufacturerId ELSE Printer.ModelName END
You can't use a CASE statement to define where conditions like that. It will be easier to just use some boolean logic
SELECT *
FROM your_table
WHERE (DATALENGTH(CostRule.ModelName) = 0
AND CostRule.Type = 1
AND CostRule.Manufacturer = Printer.ManufacturerId
AND CostRule.ColorType = 1)
OR (DATALENGTH(CostRule.ModelName) != 0
AND CostRule.Type = 2
AND CostRule.ModelName = Printer.ModelName
AND CostRule.ColorType = 1)
There are some other things that could be removed (like CostRule.ColorType = 1 since it is the same in both branches) but I've left them in here to illustrate how to transform your CASE statement into a boolean logic set.
It looks like you would just need to change the WHERE statement:
It looks like you will just need to change your WHERE statement to use OR and remove the CASE Statement.
(SELECT TOP 1
CostValue
FROM
[~client_table~].[dbo].[CostRules] AS CostRule
WHERE
DATALENGTH(CostRule.ModelName) = 0
CostRule.Type = 1
AND CostRule.Manufacturer = Printer.ManufacturerId
AND CostRule.ColorType = 1
OR
DATALENGTH(CostRule.ModelName) <> 0
AND CostRule.Type = 2
AND CostRule.ModelName = Printer.ModelName
AND CostRule.ColorType = 1
) AS MonoCost

Understanding case expression in the "Where" clause

I've got this code here and you can see from my Pseudocode what I'm trying to accomplish
select *
from dbo.BenefitsForms
inner join Dependents on BenefitsForms.UserId = Dependents.BenefitsForm_UserId
inner join CoverageLevels on BenefitsForms.MedicalId = CoverageLevels.Id
where (BenefitsForms.MedicalId > 0 AND BenefitsForms.MedicalId < 13)
AND Dependents.IsSpouse = CASE when CoverageLevels.[Level] = 2 then 1
when CoverageLevels.[Level] = 3 then 0 end
when CoverageLevels.[Level] = 4 then [any, it doesnt matter] <--- my desire but it doesn't work.
What can I do to get the effect I desire in the brackets? If Coverage Level = 4 then I don't care what Dependents.IsSpouse is, I don't even need to sort by it anymore.
Assuming that isSpouse can only be 0 or 1... if CoverageLevels.Level is 4, then compare isSpouse to itself, which will always result in true:
AND Dependents.IsSpouse = CASE
when CoverageLevels.[Level] = 2 then 1
when CoverageLevels.[Level] = 3 then 0
when CoverageLevels.[Level] = 4 then Dependents.IsSpouse
END
Alternately, this can also be expressed without the CASE:
WHERE
BenefitsForms.MedicalId > 0
AND BenefitsForms.MedicalId < 13
AND (
(Dependents.IsSpouse = 1 AND CoverageLevels.[Level] = 2)
OR (Dependents.IsSpouse = 0 AND CoverageLevels.[Level] = 3)
OR CoverageLevels.[Level] = 4
)