Using SQL aggregate results as condition in SELECT clause - sql

I am trying to resolve the issue with SQL query where I have next columns:
ITEM NUMBER and CROSS_REFFERENCE. ITEM NUMBER can have multiple values of CROSS_REFFERENCE and what I need is to count them which i can do by grouping by and count by expression. But another thing that i need is statement that say, if the ITEM NUMBER has more than one CROSS_REFFERENCE than return MULTI, otherwise return the single value of CROSS_REFFERENCE that is tied to ITEM NUMBER.
I tried to usex this expression as new coulmn:
MFG: IIf(Count([CROSS_REFERENCE])>1,"MULTI",[CROSS_REFERENCE])
But when my results returns i dont get unique list of ITEM NUMBER with ether MULTI, or value for CROSS_REFERENCE.
Any idea what am i doing wrong?
SELECT
tbl_MFG_XREF.[ITEM NUMBER],
tbl_MFG_XREF.CROSS_REFERENCE,
Count(tbl_MFG_XREF.CROSS_REFERENCE) AS CountOfCROSS_REFERENCE,
IIf(Count([CROSS_REFERENCE])>1,"MULTI",[CROSS_REFERENCE]) AS MFG
FROM
tbl_MFG_XREF
GROUP BY
tbl_MFG_XREF.[ITEM NUMBER], tbl_MFG_XREF.CROSS_REFERENCE;

You need a base query:
SELECT
[ITEM NUMBER],
Count(CROSS_REFERENCE) AS CountOfCROSS_REFERENCE,
First(CROSS_REFERENCE) AS FirstCROSS_REFERENCE
FROM
tbl_MFG_XREF
GROUP BY
tbl_MFG_XREF.[ITEM NUMBER];
Instead of First you can also use Last or Min or Max. FirstCROSS_REFERENCE will only be used if there is only one CROSS_REFERENCE for an item.
Save this query as e.g. qryItemCountCrossref
And a second query that uses it as input, e.g.
SELECT
[ITEM NUMBER],
CountOfCROSS_REFERENCE,
IIf(CountOfCROSS_REFERENCE > 1, "MULTI", FirstCROSS_REFERENCE) AS MFG
FROM qryItemCountCrossref

Related

SQL sum, multiple Group By's and Date criteria

I'm looking to perform a sum calculation on a SQL table to find the quantity of a particular stock item held against a particular salesperson up to and including a specific date.
I'm able to perform the sum function to find the quantities on a Salesperson/item basis whenever I do not factor in the date range criteria, but as soon as i add that aspect, it all goes a bit pear shaped! Here is my code so far:
SELECT Salesperson, Item No, Sum(Quantity) AS 'Quantity'
FROM dbo
WHERE (Location Code='VAN')
GROUP BY Salesperson, Item No,
HAVING (Registering Date<={ts '2017-05-03 00:00:00'})
The location code = VAN filter is required to ensure it ignores Warehouse quantities.My SQL knowledge is limited to the few instances I run into it at work and my interaction is largely based through Microsoft Query in Excel. When looking at the above code, i figured that the 'Registering date' criteria should be in the 'WHERE' section, however when i add the criteria using the options available in Microsoft Query, it creates the 'HAVING' line.
If anyone could provide any pointers, it would be much appreciated!
Cheers
Peter
I would imagine a query like this:
SELECT Salesperson, [Item No], Sum(Quantity) AS Quantity
--------------------^ escape the non-standard column name
FROM dbo.??
---------^ table name goes here
WHERE Location Code = 'VAN' AND
[Registering Date] <= '2017-05-03'
------^ put the filtering condition in the correct clause
GROUP BY Salesperson, Item No
-----------------------------^ remove the comma
Your code, as written, has multiple errors. I am guessing that most are transcription errors rather than in the original query (queries don't run if no table is given in the FROM for instance). The "major" error would then be filtering in the HAVING clause rather than the WHERE clause.

SAP BO - how to get 1/0 distinct values per week in each row

the problem I am trying to solve is having a SAP Business Objects query calculate a variable for me because calculating it in a large excel file crashes the process.
I am having a bunch of columns with daily/weekly data. I would like to get a "1" for the first instance of Name/Person/Certain Identificator within a single week and "0" for all the rest.
So for example if item "Glass" was sold 5 times in week 4 in this variable/column first sale will get "1" and next 4 sales will get "0". This will allow me to have the number of distinct items being sold in a particular week.
I am aware there are Count and Count distinct functions in Business Objects, however I would prefer to have this 1/0 system for the entire raw table of data because I am using it as a source for a whole dashboard and there are lots of metrics where distinct will be part/slicer for.
The way I doing it previously is with excel formula: =IF(SUMPRODUCT(($A$2:$A5000=$A2)*($G$2:$G5000=$G2))>1,0,1)
This does the trick and gives a "1" for the first instance of value in column G appearing in certain value range in column A ( column A is the week ) and gives "0" when the same value reappears for the same week value in column A. It will give "1" again when the week value change.
Since it is comparing 2 cells in each row for the entire columns of data as the data gets bigger this tends to crash.
I was so far unable to emulate this in Business Objects and I think I exhausted my abilities and googling.
Could anyone share their two cents on this please?
Assuming you have an object in the query that uniquely identifies a row, you can do this in a couple of simple steps.
Let's assume your query contains the following objects:
Sale ID
Name
Person
Sale Date
Week #
Price
etc.
You want to show a 1 for the first occurrence of each Name/Week #.
Step 1: Create a variable with the following definition. Let's call it [FirstOne]
=Min([Sale ID]) In ([Name];[Week #])
Step 2: In the report block, add a column with the following formula:
=If [FirstOne] = [Sale ID] Then 1 Else 0
This should produce a 1 in the row that represents the first occurrence of Name within a Week #. If you then wanted to show a 1 one the first occurrence of Name/Person/Week #, you could just modify the [FirstOne] variable accordingly:
=Min([Sale ID]) In ([Name];[Person];[Week #])
I think you want logic around row_number():
select t.*,
(case when 1 = row_number() over (partition by name, person, week, identifier
order by ??
)
then 1 else 0
end) as new_indicator
from t;
Note the ??. SQL tables represent unordered sets. There is no "first" row in a table or group of rows, unless a column specifies that ordering. The ?? is for such a column (perhaps a date/time column, perhaps an id).
If you only want one row to be marked, you can put anything there, such as order by (select null) or order by week.

Ms ACCESS and SQL: round to two decimals through query

I use queries to calculate all kinds of supplier information (average lead time, total spend for that supplier, average price, etc.). All output is shown in listboxes in forms in Ms ACCESS.
Example of a calculated number:
How do I format the output of these queries to be rounded to two decimals? I've been playing around with the listbox settings but cannot find it there. I believe I will have to do it in the query itself, but I'm not sure how.
Query code for the above number:
SELECT Avg([Item Master].PlannedLeadTime) AS AverageLeadTime
FROM [Item Master]
WHERE ((([Item Master].DateStamp)>=[Forms]![History Supplier Tool]![List2] And ([Item Master].DateStamp)<=[Forms]![History Supplier Tool]![List3]) AND (([Item Master].SupplierName)=[Forms]![History Supplier Tool]![List1]));
Note: List1 is a listbox where the user can select a certain supplier (for which the calculations are performed) and list2 and list3 are dates the user can select (as to determine a date range for the calculations).
Access SQL has a rich function set one of which is the round function.
Example:
SELECT Round(Avg([Item Master].PlannedLeadTime),2) AS AverageLeadTime
FROM [Item Master]
WHERE (...)
Further information:
http://www.techonthenet.com/access/functions/numeric/round.php
Use ROUND() Function:
The ROUND() function is used to round a numeric field to the number of decimals specified.
SQL ROUND() Syntax:
SELECT ROUND(column_name,decimals) FROM table_name;
|Parameter |Description
________________________________________________
|column_name |Required. The field to round.
|decimals |Required. Specifies the number of decimals to be returned.
So, Your required query will be:
SELECT ROUND(AVG([Item Master].PlannedLeadTime),2) AS AverageLeadTime
FROM [Item Master]
WHERE ((([Item Master].DateStamp)>=[Forms]![History Supplier Tool]![List2]
And ([Item Master].DateStamp)<=[Forms]![History Supplier Tool]![List3]) AND (([Item Master].SupplierName)=[Forms]![History Supplier Tool]![List1]));

SQL SUM query group

I have the below simple query:-
SELECT *
FROM dbo.vwPAProjects_Summary_New_2
which generates data in the following output:-
can anyone advise as to the best way to code in that when the 'PACONTNUMBER' and 'Project Type' is the same perform a sum to provide an overall total for each numerical value.
Example:-
You need to list all of your fields (don't use '*').
Then use the SUM() function on what you want summed.
Then, everything beyond the ProjectFeeAmount field will either need to be excluded from your list, or aggregated somehow (sum, min, max, etc.).
SELECT
Contract,
Sum(PAContNumber) as SumOfPAContNumber,
ProjectManagerID,
...
FROM
...
GROUP BY
Contract,
ProjectManagerID,
...
Try this:
SELECT PACONTNUMBER, Project Type,
SUM(Project_Fee_Amount) AS Project_Fee_Amount
FROM dbo.vwPAProjects_Summary_New_2
GROUP BY PACONTNUMBER, Project Type
And then add any other fields you would like to SUM to the select list.
This will get you started, you will need to add other SUM lines for the other values you want totalled
select PACONTNUMBER,
[Project Type],
sum([Project Fee Amount) as TotalProjectFees
from vwProjects_Summary_New_2
group by PACONTNUMBER,
[Project Type]

Access 2007 Crosstab Query Expression

Goal: to create a percentage column based off the values of calculated columns.
Here's the SQL code of the Crosstab query:
TRANSFORM Count(Master_Calendar.ID) AS CountOfID
SELECT Master_Calendar.Analyst, Count(Master_Calendar.ID) AS [Total Of ID]
FROM Master_Calendar
GROUP BY Master_Calendar.Analyst
PIVOT Master_Calendar.[Current Status];
This gives me a crosstab query that displays the amount of entries in the database that are "Completed", "In Process", or "Not Started", sorted by which Analyst they belong to.
What I'm trying to do is add another column to calculate the Percent Complete -- so (Completed / Total of ID) * 100. I tried putting that into an expression in another cell, but it returns with a "[Completed]" not found, even though it gives me it as an option in the Expression Builder.
Am I just naming my variables wrong, or is it not possible to do it this way? Can I reference the total count of the records that contain "Completed" using query code instead of finding out the value using a Pivot table?
Thanks for your help.
Try:
SELECT
xTab.Analyst,
[Completed]/([Total of ID]/100) AS [Complete%],
[In Process]/([Total of ID]/100) AS [In Process%],
[Not Started]/([Total of ID]/100) AS [Not Started%]
FROM xTab;