Help with SQL View involving SUM function - sql

I would like to get the following data (and more) into a single view.
SELECT Price FROM dbo.OrderItems WHERE OrderItemTypeId = 0
And
SELECT SUM (Price) AS ShippingTotal FROM dbo.OrderItems WHERE OrderItemTypeId = 1
I can’t seem to figure out how to do this with my weak SQL skills. Anybody know how I could do this?

You can use UNION statement:
SELECT Price FROM dbo.OrderItems WHERE OrderItemTypeId = 0
UNION
SELECT SUM (Price) AS ShippingTotal FROM dbo.OrderItems WHERE OrderItemTypeId = 1
But what is the semantic behind this ... In the first statement you have only one row with id = 0, in the second an aggregate function grouped by the same column (which suppose that there are more than one record with id=1). It will be helpful to show us the sample data for you table.
To improve your skills about UNION, see here: http://www.w3schools.com/sql/sql_union.asp

To cover all OrderItemTypeId...
SELECT OrderItemTypeId, SUM(Price) AS ShippingTotal
FROM dbo.OrderItems
GROUP BY OrderItemTypeId

One way would be like this:
SELECT Price, 0 AS OrderItemTypeId FROM dbo.OrderItems WHERE OrderItemTypeId = 0
UNION ALL
SELECT SUM(Price) AS Price, 1 AS OrderItemTypeId FROM dbo.OrderItems
WHERE OrderItemTypeId = 1
The 2nd column I've added to the results allows you to determine the different rows.

Related

Is it possible to aggregate the results from different rows into just one, along with the count?

So I've got a small DB that has like subsections that come under a single section. Unfortunately, the DB doesn't have a "section" column and just the subsections and they have a "Inventory" column that has either "Computer" or "Laptop" in it. I've made a query that at the very least provides me with the total count of each of these "Inventory" column against each subsection.
However, I'm trying to combine the subsections into a single row and the total count of those subsections alongside it as well. Example of what I'm trying to say:
subsections
inventory
a_subsec1
comp
a_subsec1
comp
a_subsec2
lap
a_subsec2
comp
a_subsec3
lap
a_subsec3
comp
What I'm currently getting:
d_sub
inv_count_comp
a_subsec1
2
a_subsec2
1
a_subsec3
1
What I WANT to get:
D_SUB
total_comp_count
a_sec
4
Here's the query that I'm currently running to get that second table:
SELECT DISTINCT "subsections", COUNT("inventory") FROM mytable WHERE "inventory" = 'comp' GROUP BY "subsections" ORDER BY "subsections" ASC
Thank you.
substring the column then you can treat all the row as same subsection.
with tb as(
select 'a_subsec1' sec,'comp' inv
union all
select 'a_subsec1' sec,'comp' inv
union all
select 'a_subsec2' sec,'lap' inv
union all
select 'a_subsec2' sec,'comp' inv
union all
select 'a_subsec3' sec,'lap' inv
union all
select 'a_subsec3' sec,'comp' inv
)
select msec,sum(inv_comp) total from(
select concat(substr(sec,1,1),'_sec') as msec,
case when inv='comp' then 1 else 0 end as inv_comp,
tb.*
from tb) z
group by msec
this query might not be the one you want without some modify but main idea is same.
db<>fiddle

How do I count the rows with a where clause in SQL Server?

I am pretty much stuck with a problem I am facing with SQL Server. I want to show in a query the amount of times that specific value occurs. This is pretty easy to do, but I want to take it a step further and I think the best way to explain on what I am trying to achieve is to explain it using images.
I have two tables:
Plant and
Chest
As you can see with the chest the column 'hoeveelheid' tells how full the chest is, 'vol' == 1 and 3/4 is == 0,75. In the plant table there is a column 'Hoeveelheidperkist' which tells how much plants there can be in 1 chest.
select DISTINCT kist.Plantnaam, kist.Plantmaat, count(*) AS 'Amount'
from kist
group by kist.plantnaam, kist.Plantmaat
This query counts all the chests, but it does not seperate the count of 'Vol' chests and '3/4' chests. It only does This. What I want to achieve is this. But I have no idea how. Any help would be much appreciated.
If you use group by you don't need distinct
and if you want the seprated count for hoeveelheid you ust add to the group by clause
select DISTINCT kist.Plantnaam, kist.Plantmaat, kist.hoeveelheid, count(*) AS 'Amount'
from kist
group by kist.plantnaam, kist.Plantmaat, hoeveelheid
or if you want all the 3 count ond the samw rowx you could use a condition aggreagtion eg:
select DISTINCT kist.Plantnaam, kist.Plantmaat
, sum(case when kist.hoeveelheid ='Vol' then 1 else 0 end) vol
, sum(case when kist.hoeveelheid ='3/3' then 1 else 0 end) 3_4
, count(*) AS 'Amount'
from kist
group by kist.plantnaam, kist.Plantmaat
When you want to filter the data on the counts you have to use having clause. When ever you are using aggregate functions(sum, count, min, max) and you want to filter them on aggregation basis, use having clause
select DISTINCT kist.Plantnaam, kist.Plantmaat, count(*) AS 'Amount'
from kist
group by kist.plantnaam, kist.Plantmaat having count(*) = 1 -- or provide necessary conditions

Is there a way to substitute GROUP BY

I have two tables i'm working with:
comporder(quantity,cod(Fk on cod(product),cod_ship);
product(cod(Pk),price);
I need to produce a query that will give me the sum of the prices of the products that are in the comporder table for each cod_ship;
I came up with this query:
SELECT sum(p.price),c.cod_ship
FROM product as p JOIN comporder as c
ON(p.cod=c.cod)
GROUP BY c.cod_ship;
However I am not allowed to use the GROUP BY function and I can't seem to have the price where the quanity is above one.
For exampe if in my comporder table I have:
quantity cod cod_ship
2 "1234567890" 27
3 "1234567890" 28
2 "7894561230" 28
1 "5678324515" 28
4 "1234567890" 27
1 "1234567890" 27
And if in my product table I have:
cod price
"1234567890" 20.00
"7894561230" 19.99
"5678324515" 25.99
If I apply my query the result will be:
sum cod_ship
60 27
65.979 28
When te actual result should be, based on the quantity of the products in the table comporder:
sum // cod_ship//
140 // 27//
125,97 //28//
So I can't seem to figure out how to get the sum also based on the quantity of the product and witouth the GROUP BY function, I should just show the sum as "output", can somebody help me out understand how can I do it?
REPLYING TO COMMENTS:
I cannot use group by due to an assignment.
I am using PostgreSQL 12.1
As requested by the OP in the comments here is a solution using GROUP BY:
SELECT SUM(price * quantity) as sum, cod_ship FROM comporders
INNER JOIN products ON products.cod = comporders.cod
GROUP BY cod_ship;
Edit:
Here is the solution without GROUP BY:
SELECT DISTINCT
(
SELECT SUM(price * quantity)
FROM products
INNER JOIN comporders ON products.cod = comporders.cod
WHERE cod_ship = results.cod_ship
) AS sum,
cod_ship
FROM comporders AS results;
It works by first selecting a unique list of cod_ship ids (what we previously grouped the query by).
Then we execute a subquery using the cod_ship id to calculate the sum for each column. We use the table alias results in order to reference the values in the parent query of the subquery.
SQL Fiddle Link
You can do aggregation in subselect like this:
SELECT (
SELECT SUM(p.price)
FROM product AS p
WHERE p.cod = c.cod
) AS price, c.cod_ship
FROM comporder AS c

subquery the same table in select statement

I have a resturant db and I need to total up the total value of all the items sold individually. So if I sold a hamburger that has a base price of $10.00 with bacon which costs $1.00 and a hambuger(again $10.00) with avacado that costs $0.50 I need to get $21.50 returned. My invoice table looks like this:
invoice_num item_num price item_id parent_item_id
111 hmbg 10.00 guid_1 ''
111 bacn 1.00 guid_2 guid_2
112 hmbg 10.00 guid_3 ''
112 avcd 0.50 guid_4 guid_3
I can get the sum of all the parent items like this:
SELECT item_num, SUM(price) FROM invoices WHERE parent_item_id = ''
it is the adding of the toppings that is confusing me. I feel like I need to add a subquery in the SUM but I'm not sure how to go about doing it and referencing the original query to use the item_id.
SELECT item_num, sum(i.price) + sum(nvl(x.ingred_price,0))
FROM invoices i
LEFT OUTER JOIN
(SELECT parent_item_id
, sum(price) ingred_price
FROM invoices
WHERE parent_item_id IS NOT NULL
GROUP BY parent_item_id) x
ON x.parent_item_id = i.item_id
WHERE i.parent_item_id IS NULL
GROUP BY item_num
Here's a SQL Fiddle that proves the above code works. I used Oracle, but you should be able to adapt it to whatever DB you are using.
Assumption: You don't have more than one level in a parent child relationship. E.g. A can have a child B, but B won't have any other children.
Not clear based on your question (see my comment) but as I understand it a simple group by will give you what you want. If not please explain (in the original question) why does this query does not work --- what is it missing from your requirements?
SELECT item_num, SUM(price)
FROM invoices
GROUP BY item_num
Hard to say, but looks like you need recursive cte.
Here's example for PostgreSQL:
with recursive cte as (
select
t.invoice_num, t.price, t.item_id, t.item_num
from Table1 as t
where t.parent_item_id is null
union all
select
t.invoice_num, t.price, t.item_id, c.item_num
from Table1 as t
inner join cte as c on c.item_id = t.parent_item_id
)
select invoice_num, item_num, sum(price)
from cte
group by invoice_num, item_num
sql fiddle demo
I've used null for empty parent_item_id (it's better solution than using empty strings), but you can change this to ''.

how do i get the sum of the 4th column

this statement will generate a 4 column table:
SELECT shipped.badguy AS badguy, shipped.sdate AS LineDate,
'Delivery' AS Legend, -price*quantity AS amount
FROM product JOIN shipped ON (product.id = shipped.product)
UNION
SELECT receipt.badguy, receipt.rdate,notes, amount
FROM receipt
how do i get the total sum of the 4th of column of what the above generates?
I like to use subqueries for everything.
SELECT SUM(results.amount)
FROM
(
SELECT -price*quantity AS amount
FROM product JOIN shipped ON (product.id = shipped.product)
UNION
SELECT amount
FROM
...
) results
SUM(-price*quantity)
huh?
Try
sum(price*quantity)
or combine both query as
SELECT badguy,rdate,notes,SUM(AMOUNT) FROM(
SELECT shipped.badguy AS badguy, shipped.sdate AS LineDate,
'Delivery' AS Legend, -price*quantity AS amount
FROM product JOIN shipped ON (product.id = shipped.product)
UNION
SELECT receipt.badguy, receipt.rdate,notes, amount
FROM) A
Wrap your query in another query, where the outer query just gets the sum you want. This makes your query a subquery.
SELECT SUM(amount) FROM (
SELECT shipped.badguy AS badguy, shipped.sdate AS LineDate,
'Delivery' AS Legend, -price*quantity AS amount
FROM product JOIN shipped ON (product.id = shipped.product)
UNION
SELECT receipt.badguy, receipt.rdate,notes, amount
FROM <...>
)