SQL Countifs function - sql

Hello,
I reach a dead end. I have a table with piecemark_1, piecemark_2, and weld_type.
I wanted to have a final output as per image show.
In excel I would usually use the formula "COUNTIFS+COUNTIFS" but now my data is getting bigger.
I tried to UNION both piecemark together from column piecemark_1 and piecemark_2 to create another table but I do not know how to countifs from another table.
I was wondering how can I solve this issue.

You seems want :
select piecemark, SUM(CASE WHEN WELD_TYPE = 'SW' THEN 1 ELSE 0 END) AS SW,
SUM(CASE WHEN WELD_TYPE = 'FW' THEN 1 ELSE 0 END) AS FW, COUNT(*) AS Total
from t cross apply
( values (piecemark_1), (piecemark_2)
) tt(piecemark)
group by piecemark
having count(*) > 1;
For all piecemark you need to exclude having clause.

Related

How to implement conditional COUNTIF in SQL?

I am new to SQL and facing the problem for the while.
The question is how to create such Label column in SQL?
Goal: When group count is more than 1 it should be 'Y' otherwise 'N'
Here is what I do in Excel (please see screenshot).
I think you want case with a window function:
select (case when count(*) over (partition by item) > 1 then 'Y' else 'N' end) as label

How to create an alias that counts Ws, Ls, and Ds to create a record

I have a table with sports results with a column labeled 'Result' where the values in that column are either W, L, or D. I would like to create an alias column that will quickly count the Ws, Ls, and Ds from the whole table in that columns and display it as 'Count W-Count L-Count D'.
I'm very new to SQL and I haven't figured this specific of a request out, nor can I find the correct search terms in Google to discover a video or forum result for the situation I am looking for.
If you want the values in separate columns, use conditional aggregation:
select sum(case when result = 'W' then 1 else 0 end) as w_cnt,
sum(case when result = 'L' then 1 else 0 end) as l_cnt,
sum(case when result = 'T' then 1 else 0 end) as t_cnt
from t;
Best option go for group by
Select result, count(*) from table
where column IN ('W' , 'L' , 'D' )
group by result

How do I split 1 column of data based on the value in a 2nd column in the same table?

I have a column in my database that looks like this; L for Loaded and E for Empty:
with a column in the same table with Mileage:
I'm trying to find a way to have it separate and sum() up totals for all Mileage that's Loaded and Empty into 2 columns that would say Total Loaded Mileage and Total Empty Mileage?
Something like this:
I've tried a case, self join, and possibly a pivot or view and I can't figure out how to get what I want.
You could try an IF (actually IIF in SQL Server):
COALESCE(SUM(IF(loaded = 'L', move_distance, 0)),0) AS when_loaded,
COALESCE(SUM(IF(loaded = 'E', move_distance, 0)),0) AS when_empty
The COALESCE allows for the pathologic case when the table is empty (or any additional WHERE yields no matches), and the SUM would return NULL.
Or CASE:
COALESCE(SUM(CASE WHEN loaded = 'L' THEN move_distance ELSE 0 END), 0)
Simplest in my experience is create this query as a union:
Select Loaded, move_distance Move_Loaded, 0 Move_Empty
from mytable
where Loaded = 'L'
UNION
Select Loaded, 0 , move_distance
from mytable
where Loaded = 'E'
If you want just the sums use:
Select Loaded, sum(move_distance) Move_Loaded, 0 Move_Empty
from mytable
where Loaded = 'L'
group by Loaded, 0
UNION
Select Loaded, 0 , sum(move_distance)
from mytable
where Loaded = 'E'
group by Loaded, 0
You might be able to leave out the "0" from your group by lines.
Easy way with normal sql is as below.
SELECT
SUM(CASE WHEN loaded = 'L' THEN move_distance ELSE 0 END) as
LoadedMoveDistance
SUM(CASE WHEN loaded = 'E' THEN move_distance ELSE 0 END) as
LoadedMoveDistance
FROM tablename
other way is to use Pivot which is SQL server specific it will something as below.
select [L] as Move_distance_loaded, [E] as Move_distance_empty
from
(
Select loaded, move_distance from table
) tb
PIVOT
(
SUM(move_distance)
FOR loaded IN ([L], [E])
) As pvt
you need to try pivot thing, above code will not work as exactly provided.

Query to get percent of a total using select(count)

I'm calculating the change in pain between day 1 and day 2.
There are two fields, Pain_Admit_Comfort and Pain_48_Hr_Comfort, the options in each is Yes/No.
I need to find everyone that had pain on Admit and is More Comfortable 2 days later.
This is the query. The first two statements return correct numbers. I can't figure out how to divide using the same statements as numerator and denominator.
select
(select COUNT (PAIN_48_HR_COMFORT_C)
FROM CASES WHERE PAIN_48_HR_COMFORT_C='Yes') as Forty_Eight_Hours,
(SELECT COUNT (PAIN_ADMIT_COMFORT_C)
FROM CASES WHERE PAIN_ADMIT_COMFORT_C='YES') as Admit_Uncomfort_Yes,
((select COUNT (PAIN_48_HR_COMFORT_C)
FROM CASES WHERE PAIN_48_HR_COMFORT_C='Yes')
/
(SELECT COUNT (PAIN_ADMIT_COMFORT_C)
FROM CASES WHERE PAIN_ADMIT_COMFORT_C='YES')) AS Percent_Changed
from CASES
Thanks
I don't spot any immediate problems with your statement but following statement should return the correct results and is perhaps a bit easier to read.
SELECT feh.Forty_Eight_Hours
, auy.Admit_Uncomfort_Yes
, Percent_Changed = CAST(feh.Forty_Eight_Hours AS FLOAT) / auy.Admit_Uncomfort_Yes
FROM (
SELECT Forty_Eight_Hours = COUNT(PAIN_48_HR_COMFORT_C)
FROM CASES
WHERE PAIN_48_HR_COMFORT_C = 'Yes'
) feh
CROSS APPLY (
SELECT Admit_Uncomfort_Yes = COUNT (PAIN_ADMIT_COMFORT_C)
FROM CASES
WHERE PAIN_ADMIT_COMFORT_C = 'Yes'
) auy
Your query, and the other answers, are very inefficient (multiple selects).
What you want is called a "pivot", and the most efficient way of coding it using just one select over the table (your query uses 4) is as follows:
select
sum(case when PAIN_48_HR_COMFORT_C = 'Yes' then 1 else 0 end) as Forty_Eight_Hours,
sum(case when PAIN_ADMIT_COMFORT_C = 'Yes' then 1 else 0 end) as Admit_Uncomfort_Yes
sum(case when PAIN_ADMIT_COMFORT_C = 'Yes' AND PAIN_48_HR_COMFORT_C = 'NO' then 1 else 0 end) as Improved_pain
FROM CASES
I'm not sure what the columns mean - you may need to change a 'YES' to 'NO' etc to get the "has"/"has not" pain correct.

Most optimized way to get column totals in SQL Server 2005+

I am creating some reports for an application to be used by various states. The database has the potential to be very large. I would like to know which way is the best way to get column totals.
Currently I have SQL similar to the following:
SELECT count(case when prg.prefix_id = 1 then iss.id end) +
count(case when prg.prefix_id = 2 then iss.id end) as total,
count(case when prg.prefix_id = 1 then iss.id end) as c1,
count(case when prg.prefix_id = 2 then iss.id end) as c2
FROM dbo.TableName
WHERE ...
As you can see, the columns are in there twice. In one instance, im adding them and showing the total, in the other im just showing the individual values which is required for the report.
This is a very small sample of the SQL, there are 20+ columns and w/i those columns 4 or more of them are being summed at times.
I was thinking of declaring some #Parameters and setting each of the columns equal to a #Parameter, then I could just add up which ever #Parameters I needed to show the column totals, IE: SET #Total = #c1 + #c2
But, does the SQL Server engine even care the columns are in there multiple times like that? Is there a better way of doing this?
Any reason this isn't done as
select prg.prefix_id, count(1) from tablename where... group by prg.prefix_id
It would leave you with a result set of the prefix_id and the count of rows for each prefix_ID...might be preferential over a series of count(case) statements, and I think it should be quicker, but I can't confirm for sure.
I would use a subquery before resorting to #vars myself. Something like this:
select c1,c2,c1+c1 as total from
(SELECT
count(case when prg.prefix_id = 1 then iss.id end) as c1,
count(case when prg.prefix_id = 2 then iss.id end) as c2
FROM dbo.TableName
WHERE ... ) a
Use straight SQL if you can before resorting to T-SQL procedure logic. Rule of thumb if you can do it in SQL do it in SQL. If you want to emulate static values with straight SQL try a inline view like this:
SELECT iv1.c1 + iv1.c2 as total,
iv1.c1,
iv1.c2
FROM
(
SELECT count(case when prg.prefix_id = 1 then iss.id end) as c1,
count(case when prg.prefix_id = 2 then iss.id end) as c2
FROM dbo.TableName
WHERE ...
) AS iv1
This way you logically are getting the counts once and can compute values based on those counts. However I think SQL Server is smart enough to not have to scan for the count n number of times so I don't know that your plan would differ from the SQL I sent and the SQL you have.