SQL query - group by string prefix - sql

I'm struggling with a grouping query.
I have simple table named CarParts where some car elements stored in it.
Some of those elements are available (with Type prefix "05") and some are blocked (Type prefix "01").
I want to write select query that would group my table CarParts by SerialNr and Type as shown below on the right side.

Do you want conditional aggregation?
select serialnr, name,
sum(case when type like '%-05' then amount else 0 end) as [05-available],
sum(case when type like '%-01' then amount else 0 end) as [01-blocked]
from carparts
group by serialnr, name;

You can use PIVOT to get your desired result as below-
SELECT SerialNr,
ISNULL([05-Available],0) [05-Available],
ISNULL([01-Available],0) [01-Available],
Name
FROM
(
SELECT SerialNr,Amount,Name,RIGHT( Type,2) +'-Available' AS P_Column
FROM CarParts
) AS P
PIVOT
(
SUM(Amount)
FOR P_Column IN ([01-Available],[05-Available])
) AS PVT

you can use case when
select SerialNr,Name,
sum(case when right([Type],2)='01' then amount else 0 end) as blocked_01
sum(case when right([Type],2)='05' then amount else 0 end) as availabe_05
from tbale_name group by SerialNr,Name

select SerialNr,
sum(case when Type like '%-05' then Amount else 0 end) as '05-available',
sum(case when Type like '%-01' then Amount else 0 end) as '01-blocked',
Name
from carparts
group by SerialNr, Name

Related

SQL Server Count - Group By

I have a table contain records as per below image. I want to do a count for each status and am able to do that by selecting each type of status. Which I will needs to exec 4 query to get the result. I would like to know how can I achieve that by using single query statement? Any advices or suggestion is welcome and highly appreciated. Thanks in advance.
WITH CTE(NO,STATUS)AS
(
SELECT 1,'OPEN' UNION ALL
SELECT 2,'OPEN'UNION ALL
SELECT 3,'BILLED'UNION ALL
SELECT 4,'CANCELLED'UNION ALL
SELECT 5,'BILLING'UNION ALL
SELECT 6,'BILLED'UNION ALL
SELECT 7,'CANCELLED'UNION ALL
SELECT 8,'BILLING'UNION ALL
SELECT 9,'CONFIRM'UNION ALL
SELECT 10,'IN PROGRESS'UNION ALL
SELECT 11,'OPEN'UNION ALL
SELECT 12,'CONFIRM'
)
SELECT
SUM(CASE WHEN C.STATUS='BILLED'THEN 1 ELSE 0 END)AS BILLED,
SUM(CASE WHEN C.STATUS='BILLING'THEN 1 ELSE 0 END)AS BILLING,
SUM(CASE WHEN C.STATUS='CANCELLED'THEN 1 ELSE 0 END)AS CANCELLED,
SUM(CASE WHEN C.STATUS NOT IN ('CANCELLED','BILLING','BILLED')THEN 1 ELSE 0 END)AS UNBILL
FROM CTE AS C
CTE is an example you have provided. Please replace reference to it with reference to your table

sum distinct value while using distinct id

I am working on a data that looks like this:
from the table the gender (M,F) has the same globalid, however, I need to sum the distinct globalid's value column based on the gender (total from M and F).
I have tried this code but the query just returned the same data.
select distinct (globalid) globalid, fcname, featureidentifier,
gender, source, wardcode,sum (distinct value)
from public.kano_pp
source= 'Worldpop / ORNL Adjusted'
group by globalid, fcname, featureidentifier,gender, source, wardcode, value
order by globalid;
I think you want something more like this:
select globalid,
sum(case when gender = 'F' then value else 0 end) as female_value,
sum(case when gender = 'M' then value else 0 end) as male_value
from public.kano_pp
where source = 'Worldpop / ORNL Adjusted'
group by globalid
order by globalid;
The more recent versions of Postgres support the filter clause which is a bit more efficient than the sum(case . . ).

Problems with my WHERE clause (SQL)

I'm trying to write a query that returns the following columns:
owner_id,
number_of_concluded_bookings,
number_of_declined_bookings,
number_of_inquiries
However, the problem is that my WHERE clause messes up the query because I am querying the same table. Here is the code:
SELECT owner_id,
Count(*) AS number_of_cancelled_bookings
FROM bookings
WHERE state IN ('cancelled')
GROUP BY owner_id
ORDER BY 1;
It's easy to retrieve the columns individually, but I want all of them. Say I wanted number_of_concluded_bookings as well, that would mean I'd have to alter the WHERE clause ...
Help is greatly appreciated!
Consider conditional aggregations:
SELECT owner_id,
SUM(CASE WHEN state='concluded' THEN 1 ELSE 0 END) AS number_of_concluded_bookings,
SUM(CASE WHEN state='cancelled' THEN 1 ELSE 0 END) AS number_of_cancelled_bookings,
SUM(CASE WHEN state='declined' THEN 1 ELSE 0 END) AS number_of_declined_bookings,
SUM(CASE WHEN state='inquiries' THEN 1 ELSE 0 END) AS number_of_inquiries
FROM bookings
GROUP BY owner_id

Specific where for multiple selects

I have the following problem:
I have a table that looks something like this:
ArticleID|Group|Price
1|a|10
2|b|2
3|a|3
4|b|5
5|c|5
6|f|7
7|c|8
8|x|3
Now im trying to get a result like this:
PriceA|PriceRest
13|30
Meaning I want to sum all prices from group a in one column and the sum of everything else in another column.
Something like this doesnt work.
select
sum(Price) as PriceGroupA
sum(Price) as PriceRest
from
Table
where
Group='a'
Group<>'a'
Is there a way to achieve this functionality?
SELECT
sum(case when [Group] = 'a' then Price else 0 end) as PriceA,
sum(case when [Group] <> 'a' then Price else 0 end) as PriceRest
from
Table
Please try:
select
sum(case when [Group]='A' then Price end) PriceA,
sum(case when [Group]<>'A' then Price end) PriceRest
from
Table
SQL Fiddle Demo
You just need two sub-queries:
SELECT (SELECT SUM(PRICE)
FROM Table1
WHERE [Group] ='a') AS PriceGroupA,
(SELECT SUM(PRICE)
FROM Table1
WHERE [Group]<>'a') AS PriceRest
Demo-Fiddle

Counting all other types but the current one

I'm trying to write this query, that would calculate the average value of all the columns except the one that contains the type value, which I'm grouping the whole query by.
So for 4 types for example, each column in the resulting table will contain the average of all the other three type's values, i need to exclude the current type's rows.
As an example, if I was to calculate each type's average value for itself, the query would look like:
SELECT
SUM(some value) / COUNT(TYPE)
FROM TEMPTABLE
GROUP BY TYPE
Now I'm trying to calculate the other three's total average. Thanks.
You can do one query to get the distinct types, and LEFT JOIN the same table, checking for type-inequality:
SELECT t1.type,
SUM(t2.some_value) / COUNT(t2.type)
FROM ( SELECT DISTINCT type FROM temptable ) t1
LEFT JOIN temptable t2 ON ( t1.type <> t2.type )
GROUP BY t1.type
Since you only want the average, you could replace the line
FROM ( SELECT DISTINCT type FROM temptable ) t1
by
FROM temptable t1
but the first solution might perform better, since the number of rows is reduced earlier.
The starting point here is to make a cartesian join between your types and your temptable (guessing your tables structure is : type(id, type), valueTable(id, type_id, some_value))
The following query
SELECT t.type, SUM(vt.someValue) /
COUNT (*) AS sum FROM type t,
valueTable vt WHERE vt.type_id != t.id
GROUP BY t.type
should do the trick.
Will this do what you need?
(Possibly with another CASE statement to avoid divide by zero errors if there is a possibility none of a type might be returned, I've also not explicitly accounted for the case that type is NULL)
SELECT
SUM(CASE WHEN TYPE <> 'Type1' THEN someValue ELSE 0 END) /
SUM(CASE WHEN TYPE = 'Type1' THEN 1 ELSE 0 END) AS T1,
SUM(CASE WHEN TYPE <> 'Type2' THEN someValue ELSE 0 END) /
SUM(CASE WHEN TYPE = 'Type2' THEN 1 ELSE 0 END) AS T2,
SUM(CASE WHEN TYPE <> 'Type3' THEN someValue ELSE 0 END) /
SUM(CASE WHEN TYPE = 'Type3' THEN 1 ELSE 0 END) AS T3,
SUM(CASE WHEN TYPE <> 'Type4' THEN someValue ELSE 0 END) /
SUM(CASE WHEN TYPE = 'Type4' THEN 1 ELSE 0 END) AS T4
FROM TEMPTABLE
I think that you can just use this:
SELECT type, avg(col_01)
FROM myTable
GROUP BY type
Should work on Sybase too:
SELECT
SUM(some value) / SUM(CASE WHEN TYPE = 1 THEN 1 ELSE 0 END)
FROM TEMPTABLE
GROUP BY TYPE