Cognos - Conditionally hide a column, and summarise the remaining columns - conditional-statements

I have a report with a static choice on the prompt page. The user can choose 'Full Detail', or 'Summarised'.
For a simplified example, say my report has these columns: Customer, Product, Date, Quantity, Value.
I would like to be able to show/hide the Date column based on the detail level choice, and have the Quantity and Value columns aggregate into a single Customer/Product line. I know how to show/hide the column (tying the choice variable to the column's Render Variable), but this does not do the aggregation, only makes the column invisible.
I have thought about doing a separate report page for Full Detail and Summary, but in my actual report I have a second choice box with which the user can choose a field to summarise by (e.g. Customer or Product), and the report will section-group by that field. At the moment I am doing that one per page (5 of them). Doing the detail choice the same way would mean I would need 10 pages. There is surely a better way.
Full detail:
Customer Product Date Qty Value
ABCD Things 22/10/2014 10 1.00
21/10/2014 40 4.00
23/10/2014 50 5.00
Summarised (How it looks at the moment, after hiding the Date column):
Customer Product Qty Value
ABCD Things 10 1.00
40 4.00
50 5.00
Summarised (How I would like it to look):
Customer Product Qty Value
ABCD Things 100 10.00
I am using Cognos Report Studio 10.1.1

You should not just hide column.
You should also set same value for this column in all rows
Instead of just [Date] in this column set
if (?HideDate? = 1) then ('') else ([Date])
or, if you prefer CASE
case ?HideDate? when 1 then '' else [Date] end
replace ?HideDate? = 1 with you own condition

Alexey's answer is great if you are using the standard Cognos 'auto-group and summarize' functionality.
If you have a custom aggregate that includes the [Date] column in its definition, you might squeeze a bit of performance gain out of modifying the aggregate function itself to disregard the [Date] column when a summarized total is desired.
If your aggregate function was:
total([Value] for [Customer],[Product],[Date])
..you might change this to a CASE statement like so:
CASE ?HideDate?
WHEN 1 then total([Value] for [Customer],[Product])
ELSE total([Value] for [Customer],[Product],[Date])
END
The data items after a 'for' clause usually end up in a GROUP BY clause in the resultant SQL. Limiting the items grouped, when possible, can help performance. In this case the performance improvement would likely be slight since there will only be one distinct value in Alexey's solution, but it's something to consider.

Related

Conditional styles on a calculated value in Cognos

I have a report (Pivot table) for which I have a value everyday. My goal is to calculate the variance every day and highlight with conditional styles.
1 jan. 23
2 jan. 23
3 jan. 23
5
25
42
I have a query who calculates the variance between days in % (which I dont want to put in the report).
My conditional style rule is [Table].[Pourcentage variation D-1] between 0,05 and 10.
Since my request is not in displayed my report, I have this error :
RSV-VAL-0032 The following expression is not valid. If the item exists
in a query but is not referenced in the layout, add it to a property
list.
The problem is that I don't have the "Proprety list" in my pivot table like in can have in a Data table.
How can I highlight my variance based on a request that I dont display in my Pivot table ?
Thanks for helping
Add the calculated field to the pivot table (I know you do not want this in the layout, this is just to test if that removes the error). See if the conditional style works the way you expect.
If so, change the column for the percentage data item to property, set box type to none. This way it is still something that can be referred to, but is hidden from the final result

Generate dynamic date columns in a SELECT query SQL

First of I've got a table like this:
vID
bID
date
type
value
1
100
22.01.2021
o
250.00
1
110
25.01.2021
c
100.00
2
120
13.02.2021
o
400.00
3
130
20.02.2021
o
475.00
3
140
11.03.2022
c
75.00
1
150
15.03.2022
o
560.00
To show which values were ordered(o) and charged(c) per Month, I have to like 'generate' columns for each month both ordered and charged in a MSSQL SELECT query.
Here is an example table of what I want to get:
vID
JAN2021O
JAN2021C
FEB2021O
FEB2021C
…
MAR2022O
MAR2022C
1
250.00
100.00
560.00
2
400.00
3
475.00
75.00
I need a posibility to join it in a SQL SELECT in addition to some other columns I already have.
Does anyone has an idea and could help me please?
The SQL language has a very strict requirement to know the number of columns in the results and the type of each column at query compile time, before looking at any data in the tables. This applies even to SELECT * and PIVOT queries, where the columns are still determined at query compile time via the table definition (not data) or SQL statement.
Therefore, what you want to do is only possible in a single query if you want to show a specific, known number of months from a base date. In that case, you can accomplish this by specifying each column in the SQL and using date math with conditional aggregation to figure the value for each of the months from your starting point. The PIVOT keyword can help reduce the code, but you're still specifying every column by hand, and the query will still be far from trivial.
If you do not have a specific, known number of months to evaluate, you must do this over several steps:
Run a query to find out how many months you have.
Use the result from step 1 to dynamically construct a new statement
Run the statement constructed in step 2.
There is no other way.
Even then, this kind of pivot is usually better handled in the client code or reporting tool (at the presentation level) than via SQL itself.
It's not as likely to come up for this specific query, but you should also be aware there are certain security issues that can be raised from this kind of dynamic SQL, because some of the normal mechanisms to protect against injection issues aren't available (you can't parameterize the names of the source columns, which are dependent on data that might be user-generated) as you build the new query in step 2.

Counting latest instance of multiple only based on filter context

I've got a large table of events that have occurred in an inventory of vehicles, which affect whether they are in service or out of service. I would like to create a measure that would be able to count the number of vehicles in the various inventories at any point in time, based on the events in this table.
This table is pulled from a SQL database into an Excel 2016 sheet, and I'm using PowerPivot to try to come up with the DAX measure.
Here is some example data event_list:
vehicle_id event_date event event_sequence inventory
100 2018-01-01 purchase 1 in-service
101 2018-01-01 purchase 1 in-service
102 2018-02-04 purchase 1 in-service
100 2018-02-07 maintenance 2 out-of-service
101 2018-02-14 damage 2 out-of-service
101 2018-02-18 repaired 3 in-service
100 2018-03-15 repaired 3 in-service
102 2018-05-01 damage 2 out-of-service
103 2018-06-03 purchase 1 in-service
I'd like to be able to create a pivot table in Excel (or use CUBE functions, etc) to get an output table like this:
date in-service out-of-service
2018-02-04 3 0
2018-02-14 1 2
2018-03-15 3 0
2018-06-03 3 1
Essentially, I want to be able to calculate the inventory based on any date in time. The example only has a few dates, but hopefully provides enough of a picture.
I've basically come up with this so far, but it counts more vehicles than desired - I can't figure out how to only take the latest event_sequence or event_date and use that to count the inventory.
cumulative_vehicles_at_date:=CALCULATE(
COUNTA([vehicle_id]),
IF(IF(HASONEVALUE (event_list[event_date]), VALUES (event_list[event_date]))>=event_list[event_date],event_list[event_date])
)
I tried using MAX() and EARLIER() functions, but they don't seem to work.
Edit: Added the PowerBI tag as I'm now using that software to attempt to solve this as well. See comments on Alexis Olson's answer.
I think I've found a much cleaner method than I gave previously.
Let's add two columns onto the event_list table. One which counts vehicles "in-service" on that date and one which counts vehicles "out-of-service" on that date.
InService =
VAR Summary = SUMMARIZE(
FILTER(event_list,
event_list[event_date] <= EARLIER(event_list[event_date])),
event_list[vehicle_id],
"MaxSeq", MAX(event_list[event_sequence]))
VAR Filtered = FILTER(event_list,
event_list[event_sequence] =
MAXX(
FILTER(Summary,
event_list[vehicle_id] = EARLIER(event_list[vehicle_id])),
[MaxSeq]))
RETURN SUMX(Filtered, 1 * (event_list[inventory] = "in-service"))
You can create an analogous calculated column for OutOfService or you can just take the total minus the InService count.
OutOfService =
CALCULATE(
DISTINCTCOUNT(event_list[vehicle_id]),
FILTER(event_list,
event_list[event_date] <= EARLIER(event_list[event_date])))
- event_list[InService]
Now all you have to do is put event_date on the matrix visual rows section and add the InService and OutOfService columns to the values section (use Maximum or Minimum for the aggregation option rather than Sum).
Here's the logic behind the calculated column InService:
We first create a Summary table which calculates the maximal event_sequence value for each vehicle. (We filter the event_date to only consider dates up to the current one we are working with.)
Now that we know what the last event_sequence value is for each vehicle, we use that to filter the entire table down to just the rows that correspond to those vehicles and sequence values. The filter goes through the table row by row and checks to see if the sequence value matches the one we calculated in the Summary table. Note that when we filter the Summary table to just the vehicle we are currently working with, we only get a single row. I'm just using MAXX to extract the [MaxSeq] value. (It's kind of like using LOOKUPVALUE, but you can't use that on a variable.)
Now that we've filtered the table just to the most recent events for each vehicle, all we need to do is count how many of them are "in-service". I used a SUMX here where the 1*(True/False) coerces the boolean value to return 1 or 0.
This is pretty difficult. I don't have a great answer, but here's something that kind of works.
You'll create a new calculated table where you'll calculate the status for each vehicle on each date. Start with the base cross join for each vehicle and each date:
= CROSSJOIN(VALUES(event_list[vehicle_id]), VALUES(event_list[event_date]))
Then add a calculated column to find the max sequence number for each vehicle on that date.
Sequence = MAXX(
FILTER(event_list,
event_list[event_date] <= Cross[event_date] &&
event_list[vehicle_id] = Cross[vehicle_id]),
event_list[event_sequence])
Now you can lookup the inventory value for each vehicle/sequence pair with another calculated column:
Inventory = LOOKUPVALUE(
event_list[inventory],
event_list[vehicle_id], Cross[vehicle_id],
event_list[event_sequence], Cross[Sequence])
The result should look something like this:
Once you have this, you can create a matrix using this calculated table. Put the event_date on the rows and Inventory on the columns. Filter out blank inventory values in the visual level filter and put the vehicle_id in the values field, using a count or distinct count as the aggregation method (instead of the default sum).
It should look like this:

counting and numbering in a select statement in Access SQL

Could you please help me figuring out how to accomplish the following.
I have a table containing the number of products available between one date and another as per below:
TABLE MyProducts
DateProduct ProductId Quantity Price
26/02/2016 7 2 100
27/02/2016 7 3 100
28/02/2016 7 4 100
I have created a form where users need to select a date range and the number of products they are looking for (in my example, the number of products is going to be 1).
In this example, let's say that a user makes the following selection:
SELECT SUM(MyProducts.Price) As TotalPrice
FROM MyProducts WHERE MyProducts.DateProduct
Between #2/26/2016# And #2/29/2016#-1 AND MyProducts.Quantity>=1
Now the user can see the total amount that 1 product costs: 300
For this date range, however, I want to allow users to select from a combobox also the number of products that they can still buy: if you give a look at the Quantity for this date rate, a user can only buy a maximum of 2 products because 2 is the lowest quantity available is in common for all the dates listed in the query.
First question: how can I feed the combobox with a "1 to 2" list (in this case) considering that 2 is lowest quantity available in common for all the dates queried by this user?
Second question: how can I manage the products that a user has purchased.
Let's say that a user has purchased 1 product within this date range and a second user has purchased for the very same date range the same quantity too (which is 1) for a total of 2 products purchased already in this date range. How can I see that for this date rate and giving this case the number of products actually available are:
DateProduct ProductId Quantity Price
26/02/2016 7 0 100
27/02/2016 7 1 100
28/02/2016 7 2 100
Thank you in advance and please let me know should you need further information.
You could create a table with an integer field counting from 1 to whatever max qty you could expect. Then create a query that will only return rows from your new table up to the min() qty in the MyProducts table. Use that query as the control source of your combobox.
EDIT: You will actually need two queries. The first should be:
SELECT Min(MyProducts.Quantity) AS MinQty FROM MyProducts;
which I called "qryMinimumProductQty". I create the table called "Numbering" with a single integer field called "Sequence". The second query:
SELECT Numbering.Sequence FROM Numbering, qryMinimumProductQty WHERE Numbering.Sequence<=qryMinimumProductQty.MinQty;
AFAIK there is no Access function/feature that will fill in a series of numbers in a combobox control source. You have to build the control source yourself. (Anyone with more VBA experience might have a solution to solve this, but I do not.)
It makes me ache thinking of an entire table with a single integer column only being used for a combobox though. A simpler approach to the combobox would just to show the qty available in a control on your form, give an unbound text box for the user to enter their order qty, and add a validation rule to stop the order and notify them if they have chosen a number greater than the qty on hand. (Just a thought)
As for your second question, I don't really understand what you're looking for either. It sounds like there may be another table of purchases? It should be a simple query to relate MyProducts to Purchases and take the difference between your MyProducts!qty and the Purchases!qty. If you don't have a table to store Purchases, it might be warranted based on my cursory understanding of your system.

ms sql Query for POS item sales

I have a SQL question regarding POS system item sales data. In the database, there is a "Totals" table. In that table, contains various records identified by the "TtlType" field. I'm working with 2 types. Values 11, which is the Item POS Sales, and 12, which is the Item Cost Sales.
When I do my SQL Query, i'm doing something along the lines of
SELECT ItemNumber,
SUM(ItemCount),
SUM(ItemAmount)
FROM Totals
WHERE TtlType = 11
AND Date = 8/1/2012
etc.
I'd like to also include TtlType 12. How can I merge all of the data into one row?
If I change my WHERE to include TtlType 11 & 12, I get 2 seperate rows for each menu item. The first one being TtlType 11 which is the Sell Price, and the next being 12 which is the cost. BOTH TtlType use the SAME field names to record information (ItemCount, ItemAmount)
I hope i explained this well enough. When I use the GROUP BY, I still get the same results.
I'm not sure I understand your data structure fully, or the significance of ItemNumber.
However, you don't need a GROUP BY to do SUM as you already know, but including ItemNumber in your SELECT & GROUP BY will definitely cause you to have duplicate rows as it will be grouped on that column.
You shouldn't have any issues with the two SUM functions with just
SELECT SUM(ItemCount), SUM(ItemAmount) FROM Totals WHERE TtlType IN (11,12)
AND Date = 8/1/2012