How do I get the value of the oldest date from a transaction table using a data item in Cognos 10 Report Studio? - cognos-10

How do I apply this query in Cognos Report Studio? Im thinking of creating a Data Item. Both queries are just the same, created in two different approach.
SELECT [Transaction Date], Amount
FROM DW.AmountTable
WHERE [Transaction Date] IN (SELECT Min([Transaction Date]) FROM DW.AmountTable)
SELECT A.[Transaction Date], A.[GWP Amt] [Amount]
FROM DW.AmountTable A
INNER JOIN (SELECT min(transaction date) MTD, [Policy Number])
FROM dw.amountTable
GROUP BY [Policy Number]) B
on B.MTD=A.[Transaction Date]
and A.[Policy Number] = B.[Policy Number]
where A.[Policy Number] = '7030500'
Should I create a separate Data Item for minimum(Transaction Date)?
Should I also create a new Data Item for the Amount that contains the Data Item for minimum(Transaction Date)?

The two queries you list do not do the same thing.
The first will return the earliest date for the entire table and only show rows that match that date.
The second query will fetch the earliest date for each policy number, join the main table on that date and then filter the results to only show policy number '7030500'.
To replicate the first query use this filter:
[Transaction Date] = minimum([Transaction Date] for report)
To replicate the second query use this filter:
[Transaction Date] = minimum([Transaction Date] for [Policy Number])
AND
[Policy Number] = '7030500'

Related

Sql query to calculate active count for aparticular date of every month

I have data for the user regarding his subscription transaction date.
suppose if the user has a monthly subscription and the subscription date in on 4th of every month.
Then how can I count that user as an active user for 4th of every month
Data Available:
Data Required:
Since subscription begins from October.
I believe that the following will do what you wish :-
WITH potential_dates(d) AS
(
SELECT date('2019-10-01' /* Start date */)
UNION ALL
SELECT date(d,'+1 days')
FROM potential_dates
WHERE d < '2020-01-01' /* End date */
LIMIT 1000 /* secondary/fail safe end of recursion */
)
SELECT
subscriptiondate||strftime('/%m/%Y',d) AS Date,
count() AS userCount
FROM potential_dates
JOIN subscription ON subscriptiondate = 0 + substr(d,9)
GROUP BY date
ORDER BY d
;
based upon the given data, the above results in :-
If there data were :-
Then the result would be :-

Show first n rows sorted by one column but they should be unique by another column (SQLite, Android Room)

A simple select * from mytable will return below rows. I don't know how to draw table in post so I am adding the image
As I mentioned in the question title:
(i) show first n rows sorted by one column (can be achieved using order by)
(ii) but they should be unique by another column (unique by collectionID column)
select * from mytable
order by lastAccessTime DESC;
this sorts the table in descending order according to their lastAccessTime as shown in below image:
Now I want to filter these rows according to their collectionID. So only 1 row per collectionID. I have added the image. The strikethrough rows should be removed.
Also, First n rows (lets say 30) should be returned.
I am using Android Room ORM which uses SQLite but to get the desired result set I have to write the correct query.
I think you need a window function filter here. Which will assign a row number based on collectionID and then you can just fetch only 1 row per collectionID. You may give a try to -
SELECT *
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY collectionID ORDER BY ID DESC) RN
FROM mytable) T
WHERE RN = 1
LIMIT 30;
The key idea is to "filter" the data with one query which is the source of another query. A window function can be used as in the other answer, but a basic sub-query is also sufficient:
SELECT *
FROM mytable
INNER JOIN
(SELECT Max(id) AS singleID, collectionID
FROM mytable
GROUP BY collectionID) AS filter
ON mytable.id = filter.singleID
ORDER BY lastAccessTime DESC
LIMIT 30;

Plsql wont insert because of duplicate records

So I am trying to fill a table that connect two different tables by randomly selection the id from a products table x amounts of time and then putting this id together with an id of the shops table. And then repeating this for all id from the shopa table. This way every shop gets a random amount of products; However because sometimes my randomly selected ID is the same as an id that is already in the Table for example
shop = 1 ||product =34
shop = 1 || product =20
shop = 1 || product =34
How can i prevent this from happening the code that i am trying to execute is
create or replace PROCEDURE GENERATEPRODUCTS
AS
PRODUCTTEMP NUMBER;
NROFPRODUCTS NUMBER;--total number of available products
NROFWINKELS NUMBER;--total number of shops
MAXNROFPRODUCT NUMBER;-- the maximum amount of products to be inserted
PRODUCTPERCENTAGEZONDER NUMBER;-- random percentage that will be added to 90%
PRODUCTPERCENTAGEMET NUMBER;-- total percentage of to be inserted products
WINKELS NUMBER;--counter for looping through shops
PRODUCTIDTEMP NUMBER;--the id of the product that needs to be inserted
BEGIN
PRODUCTIDTEMP :=1;
WINKELS := 1;
PRODUCTPERCENTAGEMET :=0;
PRODUCTPERCENTAGEZONDER := 0;
select count(ID)
into NROFWINKELS
FROM WINKEL;
select count(ID)
into NrofWinkels
FROM WINKEL;
select count(ID)
into NROFPRODUCTS
FROM PRODUCT;
select DBMS_RANDOM.VALUE(0,10) into PRODUCTPERCENTAGEZONDER FROM DUAL;
PRODUCTPERCENTAGEMET := (90+PRODUCTPERCENTAGEZONDER)*.010;
MAXNROFPRODUCT:=ROUND(NROFPRODUCTS*PRODUCTPERCENTAGEMET);
WHILE WINKELS <= NROFWINKELS
LOOP
WHILE MAXNROFPRODUCT<=NROFPRODUCTS
LOOP
SELECT ID
INTO PRODUCTTEMP
FROM(
SELECT ID
FROM PRODUCT
ORDER BY DBMS_RANDOM.VALUE)
WHERE ROWNUM=1;
INSERT INTO WINKEL_COUPON
("ID",WINKEL_ID,COUPON_ID)
VALUES
(PRODUCTIDTEMP,WINKELS,PRODUCTTEMP);
PRODUCTIDTEMP := PRODUCTIDTEMP+1;
END LOOP;
WINKELS := WINKELS+1;
END LOOP;
END;
In this code i want that every shop gets atleast 90% of the available products;
I think you have to put a CONSTRAINT on the table.
That way you can make sure that some columns have a unique value in them.
For example, if you want the value for ColumnShop and ColumnProduct together to be unique in the table you have to put a contstraint on the table that looks something like this:
CONSTRAINT <NameTheConstraint> PRIMARY KEY(Shop, Product)
By doing this, the table will only accept values to be inserted in the table that are unique.
So Shop = 1, Product = 34 will be inserted if that combination doesn't exist yet. If it does it will atomaticly raise an error that a constraint has been violated.

Sqlite double left outer join with count

I have the following DB structure:
tbl_record(_id,_id_user,...)
tbl_photo(_id,_id_record,...)
tbl_note(_id,_id_record,...)
When listing the records of a specific user while counting the number of photos a record has, I use the following query, which works fine:
SELECT tbl_record._id, COUNT(tbl_photo._id_record) AS photo_count FROM tbl_record
LEFT OUTER JOIN tbl_photo ON tbl_record._id=tbl_photo._id_record
WHERE tbl_record._id_user=? GROUP BY tbl_record._id;
Now, I'd like to do the same as above, but also count the number of notes a record has:
SELECT tbl_record._id, COUNT(tbl_photo._id_record) AS photo_count, COUNT(tbl_note._id_record) AS note_count FROM tbl_record
LEFT OUTER JOIN tbl_photo ON tbl_record._id=tbl_photo._id_record
LEFT OUTER JOIN tbl_note ON tbl_record._id=tbl_note._id_record
WHERE tbl_record._id_user=? GROUP BY tbl_record._id;
The count of the 2nd query does not work properly when a record has >0 photos & >0 notes, e.g. 3 photos & 5 photos which results in a count of 15 (3*5) for each.
Any idea how to make the 2nd query return the proper counts?
Thanks!!
You might be able to filter out duplicates by using COUNT(DISTINCT some_id), but this would be inefficient.
Better use correlated subqueries:
SELECT _id,
(SELECT COUNT(*)
FROM tbl_photo
WHERE _id_record = tbl_record._id
) AS photo_count,
(SELECT COUNT(*)
FROM tbl_note
WHERE _id_record = tbl_record._id
) AS note_count
FROM tbl_record
WHERE _id_user = ?

How to filter old entries with unique id out of SQL query

I have a table and a relation
I have maybe 10 Submissions, but when I query the database I only want to get those with a Unique CaseId and the one to return should be the one with the newest Date. Is it possible (And adviceable) to do this in a single query or should I do the filtering in my asp.nets code behind where I fetch the data?
Edit: New images
Here you can see that I show many items with the same case id, I only want to show the latest one (Based on date)
This is my current sql query
SELECT Submission.Id, Date, center.Name as CenterName, center.Id as CenterId, subject.Name as SubjectName, subject.Id as SubjectId, EmployeeName, Reason, Description, Explanation, Done, ChiefLevel, Action, CaseId
FROM Submission, subject, center
WHERE center.Id=CenterId AND subject.Id=SubjectId
ORDER BY Date DESC;
SELECT caseid
FROM
(
SELECT caseid, max(date) AS max_date
FROM submission
GROUP BY caseid
) a
JOIN subject t ON a.subjectid=t.id
My QUERY ended up being this
SELECT s.Id, s.Date, c.Name as CenterName, c.Id as CenterId, su.Name as SubjectName, su.Id as SubjectId, s.EmployeeName, s.Reason, s.Description, s.Explanation, s.Done, s.ChiefLevel, s.Action, s.CaseId
FROM submission as s
INNER JOIN
(
SELECT CaseId, MAX(Date) AS MaxDateTime
FROM submission
GROUP BY CaseId
) as groupeds
ON s.CaseId = groupeds.CaseId
AND s.`Date` = groupeds.MaxDateTime
INNER JOIN
(
SELECT Id, Name
FROM subject
) as su
ON su.Id=SubjectId
INNER JOIN
(
SELECT Id, Name
FROM center
) as c
ON c.Id=CenterId;

Resources