Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Kindly help,my question is in attached screenshot.
Given your table and sample data:
CREATE TABLE x ( y ) AS
SELECT 10 * LEVEL FROM DUAL CONNECT BY LEVEL <= 3;
You can update the column to add 1 five times:
UPDATE x
SET y = y + 1 + 1 + 1 + 1 + 1;
(You could simplify it by just adding 5.)
Then:
SELECT * FROM x;
Outputs:
| Y |
| -: |
| 15 |
| 25 |
| 35 |
db<>fiddle here
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I need the total and expiry date group by taluk name and taluk_code. kindly help me to group by taluk name and taluk_code.
With Total and Expiry Date:
SELECT
l.taluk_code, t.taluk_name,
count (serial_number) as Total
FROM
license_register l, taluk t where l.taluk_code=t.taluk_code and rev_district_code='17' and
l.validity_to <= now()
group by l.taluk_code, t.taluk_name
without Expiry date
SELECT
l.taluk_code, t.taluk_name,
count (serial_number) as Total
FROM
license_register l, taluk t where l.taluk_code=t.taluk_code and rev_district_code='17'
group by l.taluk_code, t.taluk_name
kindly combine and give the solution
"taluk_code" "taluk_name" "total"
"01 " "Ariyalur" 2
"04 " "Sendurai" 1
"taluk_code" "taluk_name" "ExpiryCount"
"01 " "Ariyalur" 2
"04 " "Sendurai" 1
I need the below output:
"taluk_code" "taluk_name" "total" "ExpiryCount"
"01 " "Ariyalur" 2 1
"04 " "sendurai" 1 4
SELECT
l.taluk_code,
t.taluk_name,
count(serial_number) AS total,
count(serial_number) FILTER (WHERE l.validity_to <= now()) AS expiry_count
FROM
license_register l,
taluk t
WHERE
l.taluk_code = t.taluk_code
AND rev_district_code = '17'
GROUP BY
l.taluk_code,
t.taluk_name;
filter tutorial: https://modern-sql.com/feature/filter#footnote-0
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a below kind of data in my table and i need to get the below kind of output.
U.Id Current_Id Previous_Id Date reason
01 aa null 21 xyz
01 bb aa 24 yxz
01 cc bb 24 out
01 dd cc 25 tot
01 aaa null 11 yyz
01 bbb aaa 12 zyy
First four records are one set and next two records are one set. we can identify this by current_id and Previous_ID columns. I need below kind of Output.
Output :
O1 - aa - 21 - 25 - tot
01 - aaa - 11 - 12 -zyy
For each set i need first and last record dates. How can i achieve this in ms sql?
You can use a recursive Common Table Expression (rCTE) to recurse through the data, and then get the respective MIN and MAX:
WITH YourTable AS(
SELECT *
FROM (VALUES('01','aa',NULL,21),
('01','bb','aa',24),
('01','cc','bb',24),
('01','dd','cc',25),
('01','aaa',NULL,11),
('01','bbb','aaa',12))V([U.Id],Current_Id,Previous_Id,[Date])), --A column with a . in the name is a bad idea.
--Date is an odd name for something that is clearly an int
--Solution
rCTe AS(
SELECT YT.[U.Id],
YT.Current_Id,
YT.Previous_Id,
YT.[Date],
YT.Current_Id AS Start_Id
FROM YourTable YT
WHERE Previous_ID IS NULL
UNION ALL
SELECT YT.[U.Id],
YT.Current_Id,
YT.Previous_Id,
YT.[Date],
r.Start_Id
FROM YourTable YT
JOIN rCTE r ON YT.Previous_Id = r.Current_Id)
SELECT r.[U.Id],
r.Start_Id AS Current_Id,
MIN(r.[Date]) AS StartDate,
MAX(r.[Date]) AS EndDate
FROM rCTE r
GROUP BY r.[U.Id],
r.Start_Id;
Table answers:
Answer ID | User ID | Question ID | deleted
1 | 1 | 1 | f
2 | 1 | 2 | f
3 | 1 | 2 | f
4 | 1 | 1 | t
5 | 2 | 1 | f
6 | 2 | 2 | f
7 | 2 | 2 | f
I want to select all answers distinct on (userID, questionID) using the latest answer (based on the highest id) and from this result set I want to remove all entries having deleted = t.
So my result should be
Answer ID | User ID | Question ID | deleted
3 | 1 | 2 | f
5 | 2 | 1 | f
7 | 2 | 2 | f
I guess we are not able to do it with generated query methods from the interface? I am using a #Query annotation instead:
#Query("SELECT a1 FROM answer a1 WHERE ... ")
findLatestAnswers();
I came up with this (sql fiddle: http://sqlfiddle.com/#!15/02339/8/0 ) and am not even using distinct or group by nor order by. It is doing the job but seems to be very inefficient for larger data sets? What would be a faster statement?
SELECT * FROM answer a1
WHERE NOT EXISTS ( -- where no newer answer exists
SELECT * FROM answer a2
WHERE a1.user_id = a2.user_id
AND a1.question_id = a2.question_id
AND a1.id < a2.id
)
AND a1.deleted = FALSE;
There is no problem using distinct or group by or aggregation functions. These are essential in datawarehouse or analytics software where millions or records are processed in every request (billions and trillions in bigdata).
The only adjustments are indexes generation based on your data and query.
The function you need for your scanrio is max. You have to select the max of anser_id for grouped user_id, question_id as following:
SOLUTION 1
#Query("select max(answer) from Answer answer where answer.deleted = false group by answer.userId, answer.questionId")
List<Answer> findLatestAnswersByUserQuestionNotDeleted();
This statement returns 4 record because, rightly, if you are not considering deleted answer, the latest answer of the user 1 in question 1 becomes 1.
I don't know why you didn't consider this but i will follow your question as it is.
Because of this you have to post filter programmatically deleted as described by you so the #Query becomes:
#Query("select max(answer) from Answer answer group by answer.userId, answer.questionId")
List<Answer> findLatestAnswersByUserQuestion();
Again you have, rightly, 4 records because also deleted is present and must be filtered programmatically
SOLUTION 2 (two queries, because of your requirement to ignore deleted and not consider the old one)
step 1 - findId of answers including deleted (just id):
#Query("select max(answer.id) from Answer answer group by answer.userId, answer.questionId")
List<Long> findLatestAnswersId();
step 2 - load answers by id excluding deleted
List<Answer> findAllByDeletedIsFalseAndIdIn(List<Long> ids);
SOLUTION 3 (one query)
#Query("select answer from Answer answer where answer.deleted = false and answer.id in (select max(inAnswer.id) from Answer inAnswer)")
List<Answer> findLastestNotDeleted()
I have a table with answers regarding different questions, all of them numbered. There are basically these columns: IdAnswer (unique for each answer in the table), IdUser (which won't repeat even if the same user answer questions a second time), IdQuestion and Answer.
IdAnswer IdUser IdQuestion Answer
1 John 1 0
2 John 4 1
3 John 5 1
4 John 6 0
5 Bob 1 1
6 Bob 3 1
7 Bob 5 0
8 Mark 2 0
9 Mark 7 1
10 Mark 5 0
I'd like to select from this table all answers to a specific question (say, IdQuestion = 5), and also the last question each user answered just before question number 5.
In the end I need a table that should look like this:
IdAnswer IdUser IdQuestion Answer
2 John 4 1
3 John 5 1
6 Bob 3 1
7 Bob 5 0
9 Mark 7 1
10 Mark 5 0
I've managed to make this work using a cursor to iterate through each line from the first SELECT result (which filters by IdQuestion), but I'm not sure if this is the best (and fastest) way of doing it. Is there any more efficient way of achieving the same result?
And by the way, I'm using SQL Server Management Studio 2012.
Here is one way using LEAD function
select * from
(
select *,NextQ = Lead(IdQuestion)over(partition by IdUser order by IdAnswer)
from youtable
) a
Where 5 in (IdQuestion, NextQ )
for older versions
;WITH cte
AS (SELECT prev_id = Min(CASE WHEN IdQuestion = 5 THEN rn - 1 END) OVER( partition BY IdUser),*
FROM (SELECT rn = Row_number()OVER(partition BY IdUser ORDER BY IdAnswer),*
FROM Yourtable)a)
SELECT *
FROM cte
WHERE rn IN ( prev_id, prev_id + 1 )
i need some help.
site has 2 sort types: by relevancy and date.
Sometimes happends that issues with most high score are to old, and the newest has small score.
So needed some common query based on 2 marks.
Relecancy query looks like 'ORDER BY' ts_rank(EXTENDED_INDEX, custom_tsquery('english', 'test', 0))'
and second one just 'ORDER BY table.date'
Are any ideas how improve search? Maybe some second ts_rank by date?
Based on the question it's unclear what dataset you are using as an example, but you can basically use ORDER BY rank DESC,date DESC in your query, so you will have most "recent" and highly "ranked" at the top of your result set.
WITH t(id,t,d) AS ( VALUES
(1,to_tsvector('english','one'),'2016-03-18'::DATE),
(2,to_tsvector('english','two words'),'2016-03-17'::DATE),
(3,to_tsvector('english','three words we are looking for'),'2016-03-16'::DATE),
(4,to_tsvector('english','four words goes here'),'2016-03-15'::DATE)
)
SELECT
id,
ts_rank(t,q) AS rank,
d
FROM t,to_tsquery('english','three | words') AS q
ORDER BY rank DESC NULLS LAST,d DESC;
Result :
id | rank | d
----+-----------+------------
3 | 0.0607927 | 2016-03-16
2 | 0.0303964 | 2016-03-17
4 | 0.0303964 | 2016-03-15
1 | 0 | 2016-03-18
(4 rows)