How to COUNT column values differently in a VIEW? - sql

I have a column in Datablase Table, Suppose its Observation which contains three types of values
Positive
Negative
NULL
Now I want to count the Total no of rows , Total Positive and Total Negative and some other columns. I can not use Where clause here. And its a view
So result should be like
Total Positive Negative SomeOtherCoulumn
255 80 120 Test1
315 135 65 Test2
I tried to use SQL COUNT here but could not get the desired results.

SELECT
COUNT(*) AS Total,
SUM(CASE WHEN Observation = 'Positive' THEN 1 ELSE 0 END) AS Positive,
SUM(CASE WHEN Observation = 'Negative' THEN 1 ELSE 0 END) AS Negative,
SomeOtherColumn
FROM your_view
GROUP BY SomeOtherColumn

There's an interesting technique of summing a case expression like so:
sum(case when Observation = 'Positive' then 1 else 0 end) 'TotalPositive'
The rest is easy.

Related

SQL or operator how to use with having

i have a table which i am joining with with operator. I can have 2 combinations id that table FDEL - 1 or 0 and FDVE 1 or 0, what i would like to do is to dispay if - item has fdve, or item has fdel (and count) but it doesnt work (i can see all fdve, or all fdel)
select
lpad(purchase_id,10,0) as purchase_id,
sum(has_label_fdel) as FDEL_count,
case when LABELS like '%FDVE%' then 1 else 0 end as HAS_LABEL_FDVE,
sum(has_label_fdve) as FDVE_count
from
"SRC_ORACLEIWP"."PURCHASE_ANALYSIS_RULES"
group by
lpad(purchase_id,10,0),has_label_fdve
having FDVE_count>0 -- FDEL_count>0
You want one resut row per product, so group by product only. Use SUMfor counting and MAX for the aggregated yes/no.
select
lpad(purchase_id,10,0) as padded_purchase_id,
max(has_label_fdve) as has_labels_fdve,
sum(has_label_fdve) as fdve_count,
max(has_label_fdel) as has_labels_fdel,
sum(has_label_fdel) as fdel_count
from src_oracleiwp.purchase_analysis_rules
group by padded_purchase_id
having has_labels_fdve = 1
or has_labels_fdel = 1
order by padded_purchase_id;
I've changed your alias names slightly, so they are digfferent from the columns you have (because such ambiguities can sometimes lead to problems).
The check on labels like '%FDVE%' is unnecessary, because you already have the has_label_fdve flag, which is always 0 or 1. Or so it seems. If the flags can be null, use COALESCE on them or do use LIKE expressions.
If you don't have has_label_fdve and has_label_fdel yet, use the labels column instead:
select
lpad(purchase_id,10,0) as padded_purchase_id,
max(case when labels like '%FDVE%' then 1 else 0 end) as has_labels_fdve,
sum(case when labels like '%FDVE%' then 1 else 0 end) as fdve_count,
max(case when labels like '%FDEL%' then 1 else 0 end) as has_labels_fdel,
sum(case when labels like '%FDEL%' then 1 else 0 end) as fdel_count
from src_oracleiwp.purchase_analysis_rules
group by padded_purchase_id
having has_labels_fdve = 1
or has_labels_fdel = 1
order by padded_purchase_id;

Using a case statement to show the count of two types of values in a column

SELECT
qt.name,
CASE
WHEN qr.isfinished = 0 THEN COUNT(qr.resultid)
END AS 'Attempted',
CASE
WHEN qr.isfinished = 1 THEN COUNT(qr.resultid)
END AS 'Completed'
Need it to show attempted and completed values on the same row
Name attempted Completed
--------------------------------
Algebra I 114 NULL
Algebra II 47 NULL
ASVAB 55 NULL
Algebra I NULL 69
Algebra II NULL 55
ASVAB NULL 84
Thank you for the help!
If isfinished is bit, you can't aggregate on it.
And the CASE goes inside the COUNT
SELECT qt.name,
count(Case when qr.isfinished = 0 THEN 1 END) as 'Attempted',
count(Case when qr.isfinished = 1 THEN 1 END) as 'Completed'
FROM
...
GROUP BY
qt.name
There are multiple ways you could do this, for example you could do this with joins, or you can use group by -- like so:
SELECT
qt.name,
SUM(CASE qr.isfinsihed WHEN 1 THEN 1 ELSE 0) AS 'Attempted',
SUM(CASE qr.isfinished WHEN 0 THEN 1 ELSE 0) AS 'Completed'
FROM -- what ever your from clause is, it goes here --
GROUP BY
qt.name
In order to have them on the same row, you will need to group by what they have in common. From what you have given in the question, I am assuming that is the qt.name.
Next, you can use the SUM aggregate to get each field count. All of the records that meet the criteria for each item count towards the sum, the others don't. You can also use count with 1's and Null's, I prefer using Sum because it can allow for weighted totals if I need them.

Use of sum and count inside a case statement in sql

select req.code ,res.code,
case
(
when (req.code==res.code) then 'pass'
when (req.code<>res.code) then 'fail'
/*....2 more case 'when' 'then' statements here*/
end ) result,
req.country ,res.country,
case (when then staments as above)result,
/*.......case stmts upto 70 statemnts*/
from requesttable req full outer join responsetable res on
req.id=res.id
and ....some conditions.
Can anyone tell me how can I sum every column and display the sum as well as the count of records in every column of both tables simultaneously and display count in my query?
My result should be of this sort
code code1 result sum sum1 equivalence country country1 result1 sum sum1
100 100 pass 200000 25000 fail ind aus fail 800000 800000
equivalence
pass
I am trying to prepare a report joining two tables. I am using multiple case statements to accomplish this. I want to display sum of each column and count of each column of both the tables together in a single report. The query that I have is of the following type.
I think this is kind of what you're looking for. For the code and country values displayed on the line it would give you the pass and fail accounts for the combinations displayed and you would have uniqueness on the columns the aggregate is defined on.
Select req.code,
res.code,
Sum(Case When req.code = res.code) Then 1 Else 0 End) As [Pass],
Sum(Case When req.code <> res.code) Then 1 Else 0 End) As [Fail],
req.country,
res.country,
Sum(Case When req.country = res.country) Then 1 Else 0 End) As [Pass],
Sum(Case When req.country <> res.country) Then 1 Else 0 End) As [Fail]
From requesttable req
Full Outer Join responsetable res
On req.id = res.id
Where ...
Group By req.code,
res.code,
req.country,
res.country

Count the "ratio?" for wins and losses

I've already got this to work but it's a really bad approach and i need some help with factorization of my query.
SELECT `GameDate`,
COUNT(CASE
WHEN `P1Outcome`= 'win' AND P2Param = 'a' THEN 1
END) AS a_win,
COUNT(CASE
WHEN `P1Outcome`= 'loss' AND P2Param = 'a' THEN 1
END) AS a_loss,
COUNT(CASE
WHEN `P1Outcome`= 'win' AND P2Param = 'b' THEN 1
END) AS b_win,
COUNT(CASE
WHEN `P1Outcome`= 'loss' AND P2Param = 'b' THEN 1
END) AS b_loss
FROM games
WHERE `P2Param` IN ( 'a', 'b', 'c' )
GROUP BY GameDate
This will get me an query that i can use in my php application but i would like to skip having to make the actual ratio calculation in php and fetch it directly with SQL.
So basically what i've been trying to do is something similar to this:
COUNT(CASE
WHEN `P1Outcome`= 'win' AND P2Param = 'a' THEN 1 Else -1
END) AS a_ratio,
But just as the beginer i'm, i can't figure it out how i can make this to work.
EDIT:
Sorry for not explaining my regards in more details, here is the thing. I'm creating an statistics component and i need to fetch the ratio for a period of time in order to display it as an graph. So the following things are required:
GameDate (1,2,3,4... days ago)
The ratio for the player based on to different params (maps in this case)
So in short this is what i got at the moment:
GameDate a_win a_loss b_win b_loss
2011/04/25 x x x x
2011/04/23 x x x x
....
So everything works out great, but i would like to have the actual ratio calculation made in SQL because at the moment i need to make it in php e.g $ratio = $q[a_win]-$q[a_loss] and due to the fact that I've a lot of different param my query is like double the size because i need to fetch both the win and loss instead of just the ratio like i want in the first place.
SELECT `GameDate`,
SUM(CASE `P2Param`
WHEN 'a' THEN CASE P1Outcome WHEN 'win' THEN 1 ELSE -1 END
ELSE 0
END) AS a_ratio,
SUM(CASE `P2Param`
WHEN 'b' THEN CASE P1Outcome WHEN 'win' THEN 1 ELSE -1 END
ELSE 0
END) AS b_ratio
FROM games
WHERE `P2Param` IN ( 'a', 'b', 'c' )
GROUP BY GameDate
What is very important COUNT just returns number of rows regardless of what you count unless you use COUNT(DISTINCT ...) which in turn returns count of distinct values. To sum up some values which you produce for every row use SUM(...). Make sure what happens in your DBMS when an expression in the SUM() function evaluates to NULL - some databases will just make the whole SUM return NULL.
To get ratio of any kind of data you can do:
select _date_, (SUM(case when _your_test_ then 1 else 0 end) / count(1)) as ratio
from _yout_table_
group by _date_
And if you just want to calculate a sum of some values:
select _date_, SUM(case when _your_test_ then 1 else 0 end) as number_of_something
from _yout_table_
group by _date_
What about:
SELECT COUNT(id), P1Outcome, P2Param
FROM games
GROUP BY P2Param, P1Outcome
It will returns you a resultset with 3 columns:
counted values for param and outcome
outcome
param
With that you can do more in my opinion.
SELECT GameDate, P2Param, SUM(CASE WHEN P1Outcome = 'win' THEN 1 ELSE -1 END) AS ratio
FROM games
GROUP BY GameDate, P2Param

SQL - Count( ) issue

I have a table with a charge/credit column:
Item | PriceVal | CostVal | CHARGE_CODE
1 5 3 CH
2 8 5 CH
1 -5 -3 CR
3 7 1 CH
4 15 10 CH
1 5 3 CH
I've got the query I need to get the NET price and cost, but I'm also interested in the NET charges. Right now I have:
SELECT Item, SUM(PriceVal), SUM(CostVal)
FROM Table
GROUP BY Item
How do I get another column with the value
COUNT(SUM(CHARGE_CODE=CH)-SUM(CHARGE_CODE=CR))
I'm at a loss.
count() is going to count one for every value thats not null, so I don't think thats exactly what you want. Take the count out and just take the
sum(case when charge_code = CH then costval else 0 end)
- sum(case when charge_code = 'CR' then costval else 0 end)
Since you have the dollar values entered as negatives in the table already, you can use the simple formula:
select
Item,
sum(PriceVal),
sum(CostVal),
sum(PriceVal-CostVal)
from Table
group by Item
I don't believe you should be subtracting the credit items as they're already negative.
If you really do want want the net count of transactions:
select
Item,
sum(PriceVal),
sum(CostVal),
sum(case when charge_code = 'CH' then 1 else 0 end) -
sum(case when charge_code = 'CR' then -1 else 0 end)
from Table
group by Item
or, if there are only two charge codes, substitute:
sum(case when charge_code = 'CH' then 1 else -1 end)
for the last column.
Not 100% sure what you want, but you can count only certain rows like this:
SELECT COUNT(IF(CHARGE_CODE=CH,1,NULL)) ...
And similarly sum certain values from certain rows like this:
SELECT SUM(IF(CHARGE_CODE=CH,PriceVal,0)) ...