How do you create a totals row with percentage in SQL - sql

I have SQL that generates output like that shown in the attached image under "FIGURE A", but need to expand it to look like "FIGURE B".
Can anyone assist with the SQL? Thanks

don't know what Database you are using so try Oracle.
First you need to create a new table include the new column PERCENT_COMPLETED
select STATE,WIDGETS_REQUIRED,WIDGETS_COMPLETED,
WIDGETS_COMPLETED/WIDGETS_REQUIRED*100 | '%' as PERCENT_COMPLETED
from table;
then you need to insert a new row into it
select
'Total' as STATE,
sum(WIDGETS_REQUIRED) as WIDGETS_REQUIRED,
sum(WIDGETS_COMPLETED) as WIDGETS_COMPLETED,
sum(WIDGETS_COMPLETED)/sum(WIDGETS_REQUIRED)*100 | '%' as PERCENT_COMPLETED
into new_table
from table;

In MYSQL, I tried this solution.
First, insert a row with 3 values: STATE, WIDGETS_REQUIRED, WIDGETS_COMPLETED. You can insert these 3 values later, but it is more convenient insert them now.
insert into FIGURE_A values
("TOTAL", 48, 33);
Second, add a column: percent_complete
alter table FIGURE_A
ADD percent_complete decimal(5,2);
Here you should notice that you need to add a constraint. See this question.
So, we need to add the check constraint:
alter table FIGURE_A
ADD constraint chk_range CHECK (percent_complete>=0 and percent_complete<=100);
Finally, we just add the percentage values. See here. There are many ways to calculate the percentage. And this question is more suitable for your case, because you need to update, not just calculate.
update FIGURE_A
set percent_complete = WIDGETS_COMPLETED*100/WIDGETS_REQUIRED
The final result may look like this.

Related

How to replace all the NULL values in postgresql?

I found the similar question and solution for the SQL server. I want to replace all my null values with zero or empty strings. I can not use the update statement because my table has 255 columns and using the update for all columns will consume lots of time.
Can anyone suggest to me, how to update all the null values from all columns at once in PostgreSQL?
If you want to replace the data on the fly while selecting the rows you need:
SELECT COALESCE(maybe_null_column, 0)
If you want the change to be saved on the table you need to use an UPDATE. If you have a lot of rows you can use a tool like pg-batch
You can also create a new table and then swap the old one and the new one:
# Create new table with updated values
CREATE TABLE new_table AS
SELECT COALESCE(maybe_null_column, 0), COALESCE(maybe_null_column2, '')
FROM my_table;
# Swap table
ALTER TABLE my_table RENAME TO obsolete_table;
ALTER TABLE new_table RENAME TO my_table;

Microsoft SQL Server - Copy column in table, modify value and type

I'm quite new to scripts and need some help on creating a script doing multiple actions in sequence.
Let's use this tentative (and bisarre) table to illustrate the solution. The table could potentially hold hundreds of entries:
I want to add a PhoneNumber column with varchar type and populate it from the existing PhoneNumber column.
For phone numbers consiting of 5 digits I want to add a leading zero (0) so all entries have the same length (6).
When this is done for all occurances of 5-digit phone numbers I want to delete the old PhoneNumber column
This is how the table should look after step 1:
And after step 2 it should look like this:
Finally, after the third step I want this outcome:
Can this be accomplished with a script? I don't really need the script to follow this exact sequence as long as it results in the desired outcome. This is just the sequence of actions I have thought could be an allright approach.
Here you go
Remember, you can't have 2 columns called the same
ALTER TABLE [TABLENAME] ADD PHONENUMBERCHAR char(6); --Adds a new column
GO;
UPDATE [TABLENAME] SET PHONENUMBERCHAR = RIGHT(CONCAT('000000', PHONENUMBER), 6); --Updates the value
GO;
ALTER TABLE [TABLENAME] DROP COLUMN PHONENUMBER --Deletes the old column
If the value is really an integer, you can use format():
select id, phonenumber, format(phonenumber, '000000')
from t;
You may want to add this as a computed column:
alter table t add phonenumber_6 as (format(phonenumber, '000000'));

How to delete specific column values in multiple "insert into" query

Sorry if you think my question is too basic, because i'm a newbie.
Lets say i have 1000 lines of query like this
INSERT INTO table (column1,column2,column3) VALUES (1,2,3);
INSERT INTO table (column1,column2,column3) VALUES (3,33,333);
....
I want to delete column2 with its value, Is there any way so that i dont need to delete 1000 rows manualy. Thanks.
Perhaps you want to completely drop the second column:
ALTER TABLE yourTable DROP COLUMN column2;
Although you may have used many statements to build up the data in your table, dropping a particular column only requires a one-liner.

Common methods for doing select with computation by need?

I would like to be able to add columns to a table with cells who's values are computed by need at 'querytime' when (possibly) selecting over them.
Are there some established ways of doing this?
EDIT: Okay I can do without the 'add columns'. What I want is to make a select query which searches some (if they exist) rows with all needed values computed (some function) and also fills in some of the rows which does not have all needed values computed. So each query would do it's part in extending the data a bit.
(Some columns would start out as null values or similar)
I guess I'll do the extending part first and the query after
You use select expression, especially if you don't plan to store the calculation results, or they are dependant on more than one table. An example, as simple as it could be:
SELECT id, (id+1) as next_id FROM table;
What type of database are you asking for? If it is SQL Server then you can use the computed columns by using the AS syntax.
Eg:
create table Test
(
Id int identity(1,1),
col1 varchar(2) default 'NO',
col2 as col1 + ' - Why?'
)
go
insert into Test
default values
go
select * from Test
drop table Test
In the SQL world it's usually expensive to add a column to an existing table so I'd advise against it. Maybe you can manage with something like this:
SELECT OrderID,
ProductID,
UnitPrice*Quantity AS "Regular Price",
UnitPrice*Quantity-UnitPrice*Quantity*Discount AS "Price After Discount"
FROM order_details;
If you really insist on adding a new column, you could go for something like (not tested):
ALTER TABLE order_details ADD column_name datatype
UPDATE order_details SET column_name = UnitPrice+1
You basically ALTER TABLE to add the new column, then perform an UPDATE operation on all the table to set the value of the newly added column.

Multiplying two columns of same table and storing result to the third column of same table

I m having a table
SALES(sno,comp_name,quantity,costperunit,totalcost)
After supplying the costperunit values, totalcost need to be calculated as "totalcost=quantity*costperunit".
I want to multiply 'quantity' and 'costperunit' columns and store the result in 'totalcost' column of same table.
I have tried this:
insert into SALES(totalcost) select quantity*costperunit as res from SALES
But It failed!
Somebody please help me in achieving this..
Thanks in Advance
Try updating the table
UPDATE SALES SET totalcost=quantity*costperunit
You need to use update.
UPDATE SALES SET totalcost=quantity*costperunit
It would be better if you do not calculate this field manually but make it a computed column instead - so it calculates automatically for you.
You can change the column with following query:
ALTER TABLE Sales
DROP COLUMN totalcost
ALTER TABLE Sales
ADD totalcost AS quantity*costperunit
DEMO
try this while inserting new row
INSERT INTO test(sno,comp_name,quantity,costperunit,totalcost)
Values (1,#comp_name,#quantity,#costperunit,#quantity*#costperunit)
Best not to store fields that can be calculated, but if you want to, with SQL Server you can set a field to be calculated automatically when values are there.