Sum values of two columns row in SQL - sql

Below is the query I have prepared to fetch the details from the database.
select vUI.ArticleID , vUCS.NumInstalled,vUCS.NumPresent, vUCS.NumPending, vUCS.NumFailed, vUCS.NumNotApplicable , vUCS.NumMissing, vUCS.NumUnknown , vUCS.NumTotal
from v_Update_DeploymentSummary_Live vUCS
inner join v_UpdateInfo vUI
on vUCS.CI_ID=vUI.CI_ID
where vUCS.CollectionID='RA00686' --or vUCS.CollectionID='RA00785'
There are a couple of things I tried to achieve but getting hard time.
Below is the output data.
I am hoping that screenshot should be visible. but in case if its missing I would like to add values of vUCS.NumInstalled and vUCS.NumPresent as both are showing data for success.
How can I add the value of two columns in a row?
My query is little bit slow due to vUCS.CollectionID='RA00686' or vUCS.CollectionID='RA00785', I am trying to change it as it is taking more than 3 minutes to run.
Current Output
ArticleID NumInstalled NumPresent NumPending
4484107 2 16 2
4519998 0 0 0
4521860 7573 7738 13
Expected Output
ArticleID NumInstalled NumPending
4484107 18 2
4519998 0 0
4521860 15311 13

Try the below:
select vUI.ArticleID ,
ISNULL(vUCS.NumInstalled,0)+ISNULL(vUCS.NumPresent,0) AS NumInstalled,
vUCS.NumPending
from v_Update_DeploymentSummary_Live vUCS
inner join v_UpdateInfo vUI
on vUCS.CI_ID=vUI.CI_ID
where vUCS.CollectionID='RA00686'
And you have to create an Index for the vUCS.CollectionID column to increase the query performance.
CREATE NONCLUSTERED INDEX NCX_v_Update_DeploymentSummary_Live_Indx1 ON v_Update_DeploymentSummary_Live(CollectionID)

Related

Max match same numbers from each row

To generate 1mln rows of report with the below mentioned script is taking almost 2 days so, really appreciate if somebody could help me with different script which the report can be generated within 10-15mins please.
The requirement of the report is as following;
Table “cover” contains 5mln rows & 6 columns of data and likewise table “data” contains 500,000 rows and 6 columns.
So, each numbers of the rows in table cover has to go through table date and provide the maximum matches.
For instance, as mentioned on the below tables, there could be 3 matches in row #1, 2 matches in row #2 and 5 matches in row #3 so the script has to select the max selection which is 5 in row #3.
Sample table
UPDATE public.cover_sheet AS fc
SET maxmatch = (SELECT MAX(tmp.mtch)
FROM (
SELECT (SELECT CASE WHEN fc.a=drwo.a THEN 1 ELSE 0 END) +
(SELECT CASE WHEN fc.b=drwo.b THEN 1 ELSE 0 END) +
(SELECT CASE WHEN fc.c=drwo.c THEN 1 ELSE 0 END) +
(SELECT CASE WHEN fc.d=drwo.d THEN 1 ELSE 0 END) +
(SELECT CASE WHEN fc.e=drwo.e THEN 1 ELSE 0 END) +
(SELECT CASE WHEN fc.f=drwo.f THEN 1 ELSE 0 END) AS mtch
FROM public.data AS drwo
) AS tmp)
WHERE fc.code>0;
SELECT *
FROM public.cover_sheet AS fc
WHERE fc.maxmatch>0;
As #a_horse_with_no_name mentioned in the comment to the question, your question is not clear...
Seems, you want to get the number of records which 6 fields from both tables are equal.
I'd suggest to:
reduce the number of select statements, then the speed of query execution will increase,
split your query into few smaller ones (good practice), to check your logic,
use join to get equal data, see: Visual Representation of SQL Joins
use subquery or cte to get result on which you'll be able to update table.
I think you want to get result as follow:
SELECT COUNT(*) mtch
FROM public.cover_sheet AS fc INNER JOIN public.data AS drwo ON
fc.a=drwo.a AND fc.b=drwo.b AND fc.c=drwo.c AND fc.d=drwo.d AND fc.e=drwo.e AND fc.f=drwo.f
If i'm not wrong and above query is correct, the time of execution of above query will reduce to about 1-2 minutes.
Finally, update query may look like:
WITH qry AS
(
-- proper select statement here
)
UPDATE public.cover_sheet AS fc
SET maxmatch = qry.<fieldname>
FROM qry
WHERE fc.code>0 AND fc.<key> = qry.<key>;
Note:
I do not see your data and i know nothing about its structure, relationships, etc. So, you have to change above query to your needs.

Pivot table Non-unique values

I have two tables that I want to join together into 1 row by accessruleId for an ssrs report. The issue is FieldName has dynamic values and the same fieldName could appear more than once It seems like Pivot table is what I want but examples I've looked at is pivoting off a unique value and doing an aggregate function. Below is the output for query 1 and 2 and I want to combine the results so it looks like screenshot 3. If a given fieldname shows up more than once (businessArea in this case) I want to make the values comma delimited. Any links to examples similar to my need would be greatly appreciated. I'm using sql server 2016
Query 1
select ar.AccessRuleId, ar.EffectiveDate, ar.TermDate, ar.CreatedByUser, ar.LastUpdatedUser
from [AccessRule].[AccessRule] ar
where ar.AccessRuleId = 1
Query 2
select rf.FieldName, ro.[Value]
from [AccessRule].[RuleOperation] ro
join [AccessRule].[RuleField] rf on ro.FieldId = rf.RuleFieldId
where ro.AccessRuleId = 1

SQL: Select Top 2 Query is Excluding Records with more than 2 Records

I just joined after having a problem writing a query in MS Access. I am trying to write a query that will pull out the first two valid samples in from a list of replicated sample results and then would like to average the sample values. I have written a query that does pull samples with only two valid samples and averages these values. However, my query doesn't pull samples where there are more than two valid sample results. Here's my query:
SELECT temp_platevalid_table.samp_name AS samp_name, avg (temp_platevalid_table.mean_conc) AS fin_avg, count(temp_platevalid_table.samp_valid) AS sample_count
FROM Temp_PlateValid_table
WHERE (Temp_PlateValid_table.id In (SELECT TOP 2 S.id
FROM Temp_PlateValid_table as S
WHERE S.samp_name = S.samp_name and s.samp_valid=1 and S.samp_valid=1
ORDER BY ID))
GROUP BY Temp_PlateValid_table.samp_name
HAVING ((Count(Temp_PlateValid_table.samp_valid))=2)
ORDER BY Temp_PlateValid_table.samp_name;
Here's an example of what I'm trying to do:
ID Samp_Name Samp_Valid Mean_Conc
1 54d2d2 1 15
2 54d2d2 1 20
3 54d2d2 1 25
The average mean_conc should be 17.5, however, with my current query, I wouldn't receive a value at all for 54d2d2. Is there a way to tweak my query so that I get a value for samples that have more than two valid values? Please note that I'm using MS Access, so I don't think I can use fancier SQL code (partition by, etc.).
Thanks in advance for your help!
Is this what you want?
select pv.samp_name, avg(pv.value_conc)
from Temp_PlateValid_table pv
where pv.samp_valid = 1 and
pv.id in (select top 2 id
from Temp_PlateValid_table as pv2
where pv2.samp_name = pv.samp_name and pv2.samp_valid = 1
)
group by pv.samp_name;
You might need avg(pv.value_conc * 1.0).

Multicriteria Insert/Update

I'm trying to create a query that will insert new records to a table or update already existing records, but I'm getting stuck on the filtering and grouping for the criteria I want.
I have two tables: tbl_PartInfo, and dbo_CUST_BOOK_LINE.
I'm want to select from dbo_CUST_BOOK_LINE based upon the combination of CUST_ORDER_ID, CUST_ORDER_LINE_NO, and REVISION_ID. Each customer order can have multiple lines, and each line can have multiple revision. I'm trying to select the unique combinations of each order and it's connected lines, but take the connected information for the row with the highest value in the revision column.
I want to insert/update from dbo_CUST_BOOK_LINE the following columns:
CUST_ORDER_ID
PART_ID
USER_ORDER_QTY
UNIT_PRICE
I want to insert/update them into tbl_PartInfo as the following columns respectively:
JobID
DrawingNumber
Quantity
UnitPrice
So if I have the following rows in dbo_CUST_BOOK_LINE (PART_ID omitted for example)
CUST_ORDER_ID CUST_ORDER_LINE_NO REVISION_ID USER_ORDER_QTY UNIT_PRICE
SCabc 1 1 0 100
SCabc 1 2 4 150
SCabc 1 3 4 125
SCabc 2 3 2 200
SCxyz 1 1 0 0
SCxyz 1 2 3 50
It would return
CUST_ORDER_ID CUST_ORDER_LINE_NO (REVISION_ID) USER_ORDER_QTY UNIT_PRICE
SCabc 1 3 4 125
SCabc 2 3 2 200
SCxyz 1 2 3 50
but with PART_ID included and without REVISION_ID
So far, my code is just for the inset portion as I was trying to get the correct records selected, but I keep getting duplicates of CUST_ORDER_ID and CUST_ORDER_LINE_NO.
INSERT INTO tbl_PartInfo ( JobID, DrawingNumber, Quantity, UnitPrice, ProductFamily, ProductCategory )
SELECT dbo_CUST_BOOK_LINE.CUST_ORDER_ID, dbo_CUST_BOOK_LINE.PART_ID, dbo_CUST_BOOK_LINE.USER_ORDER_QTY, dbo_CUST_BOOK_LINE.UNIT_PRICE, dbo_CUST_BOOK_LINE.CUST_ORDER_LINE_NO, Max(dbo_CUST_BOOK_LINE.REVISION_ID) AS MaxOfREVISION_ID
FROM dbo_CUST_BOOK_LINE, tbl_PartInfo
GROUP BY dbo_CUST_BOOK_LINE.CUST_ORDER_ID, dbo_CUST_BOOK_LINE.PART_ID, dbo_CUST_BOOK_LINE.USER_ORDER_QTY, dbo_CUST_BOOK_LINE.UNIT_PRICE, dbo_CUST_BOOK_LINE.CUST_ORDER_LINE_NO;
This has been far more complicated that anything I've done so far, so any help would be greatly appreciated. Sorry about the long column names, I didn't get to choose them.
I did some research and think I found a way to make it work, but I'm still testing it. Right now I'm using three queries, but it should be easily simplified into two when complete.
The first is an append query that takes the two columns I want to get distinct combo's from and selects them and using "group by," while also selecting max of the revision column. It appends them to another table that I'm using called tbl_TempDrop. This table is only being used right now to reduce the number of results before the next part.
The second is an update query that updates tbl_TempDrop to include all the other columns I wanted by setting the criteria equal to the three selected columns from the first query. This took an EXTREMELY long time to complete when I had 700,000 records to work with, hence the use of the tbl_TempDrop.
The third query is a basic append query that appends the rows of tbl_TempDrop to the end destination, tbl_PartInfo.
All that's left is to run all three in a row.
I didn't want to include the full details of any tables or queries yet until I ensure that it works as desired, and because some of the names are vague since I will be using this method for multiple query searches.
This website helped me a little to make sure I had the basic idea down. http://www.techonthenet.com/access/queries/max_query2_2007.php
Let me know if you see any flaws with the ideology!

what's the difference between SQL's

I work with Databases not extensively but to the point where I can write Selects, update's ,small joins etc..
I can get my work done with my current knowledge. I have encountered some difficulty while trying to complete a task, I got the task completed but would like to understand why some of the SQL's that I have written in process did not work.
Task at hand: I have a table "TESTTABLE" that has 5 columns and the 6th is the sum of these 5 columns.
Currently table looks like below:
ID NAME SUB1 SUB2 SUB3 SUB4 SUB5 TOTAL
1 VA 10 20 30 40 50
2 MI 20 40 60 80 10
3 NC 10 30 50 70 90
4 SC 10 20 30 40 50
5 WA 20 40 60 80 15
the last column 'Total' is currently empty.
Now,I need to update the total column in the table with the sum(sub1+sub2=sub3+sub4+sub5).
In this process I have written the following SQL's and it did work, would like to understand the difference.
Attempt1:
UPDATE TESTTABLE T
SET Total =
SELECT (sub1+sub2+sub3+sub4+sub5)
FROM TESTTABLE TB
WHERE T.ID = TB.ID);
Error encountered:--ERROR: (2) This form of correlated query is not supported - consider rewriting;
Attempt2:
CREATE TABLE TEMP_TESTTABLE AS( SELECT ID, SUM(sub1+sub2+sub3+sub4+sub5) AS SUB_TOTAL FROM TESTTABLE )
UPDATE TESTTABLE A
SET TOTAL =
(SELECT SUB_TOTAL
FROM TEMP_TESTTABLE B
WHERE B.ID=A.ID);
ERROR encountered: ERROR: (2) This form of correlated query is not supported - consider rewriting
Attempt3:
UPDATE TESTTABLE
SET TOTAL = SUM(sub1+sub2+sub3+sub4+sub5);
ERROR encountered: ERROR: Aggregate functions not allowed in the set list of an UPDATE statement
Attempt4- Successful one;
UPDATE TESTTABLE A
SET TOTAL = B.SUB_TOTAL FROM TEMP_TESTTABLE B
WHERE A.ID=B.ID
Attempt 4 worked for me by using the temp table created in attempt2 [TEMP_TESTTABLE].
I need some detail explanation, and appreciate if anyone can provide me and let me know how my attempt4 is different than 1,2,3.
Help is greatly appreciated.
Thanks,
Attempt1 failed because subqueries should be enclosed in parentheses.
UPDATE TESTTABLE T
SET Total =
(SELECT (sub1+sub2+sub3+sub4+sub5)
FROM TESTTABLE TB
WHERE T.ID = TB.ID);
Attempt2 failed because SUM() function is aggregate function, to sum values from multiple rows, not to sum values from multiple columns in one row.
You should redefine the column as a computed column, like this
Alter table TESTTABLE
add column Total as sub1+sub2+sub3+sub4+sub5
This is the cannonical Soluion.
UPDATE
TESTTABLE
SET
Total = (sub1+sub2+sub3+sub4+sub5)
The reason the others failed is that you where doing subselects that returned multiple rows. You didn't tell the UPDATE how the different rows mapped from the select to the UPDATE.
In this version you are making it simple - one table - on each row set a value on that row based on the data in that row.
In your final version you're doing the same but in a redundant way (extra join that does nothing).