How to format SQL subquery to produce new and old data - sql

I have a database where I am trying to figure out this problem. I want to write a SQL query to list all patients whose information has changed during their future visits. A future visit is defined as dbo.patientvisit.encounter_id < dbo.visitvitalstat.encounter_id The outputs I want in the table are the columns patient number, old and new race values, old and new gender values, and both encounter ids from the both tables. The new race and gender values are from future visits.
This is the code I have so far but I can't figure out how to get the new gender and new race values.
SELECT pv.patient_nbr,pv.encounter_id, vvs.race, vvs.gender, vvs.encounter_id
FROM PatientVisit pv
LEFT JOIN VisitVitalStat vvs
ON pv.encounter_id = vvs.encounter_id
WHERE pv.encounter_id < vvs.encounter_id;
This is the result I should get back:
SELECT  fpv.patient_nbr(??)
                vvs.race as "Old race",
                fv.newrace as "New Race",
                vvs.gender as "Old Gender",
                fv.newgender as " New Gender",
                vvs.encounter_id as "Old Encounter ID" ,
                fv.newencounter as "New Encounter ID"
FROM  VisitVitalStat vvs
INNER JOIN
                    ( SELECT fpv.patient_nbr as newnbr,
                                      fvvs.race as newrace,
                                      fvvs.gender as newgender,
                                      fvvs.encounter_id as newencounter
FROM PatientVisit fpv, VisitVitalStat fvvs
                      WHERE  fpv.encounter_id = fvvs.encounter_id
                              AND
                                      fpv.encounter_id < fvvs.encounter_id) fv
ON   fv.newencounter = vvs.encounter_id;
So I was able to write a query but I feel like it is still off, I'm not sure how to get patient number into all of this.

One method uses lag():
select pv.*
from (select pv.*,
lag(gender) over (partition by patient_nbr order by encounter) as prev_gender,
lag(race) over (partition by patient_nbr order by encounter) as prev_race,
lag(encounter) over (partition by patient_nbr order by encounter) as prev_encounter
from patientvisit pv
) pv
where prev_gender <> gender or prev_race <> race;

You can adapt this solution. Where b1 will be the old data and b2 the new data.
with base as (
select
patient_nbr
,encounter_id
,row_number() over (partition by patient_nbr order by encounter_id asc) as row
from patientvisit
LEFT JOIN VisitVitalStat vvs
ON pv.encounter_id = vvs.encounter_id
)
select b1.patient_nbr
,b1.encounter_id as old
,b2.encounter_id as new
,b1.gender as old
,b2.gender as new
,b1.race as old
,b2.race as new
from base b1
join base b2 on
b1.patient_nbr=b2.patient_nbr
and b1.row+1=b2.row

Related

Structuring looker Explore Results

I’m having trouble figuring out how to count publications in my Looker data set by year and author. In my Looker explore the data Looker table results look like this:
Pub_id
year
author
author_id
1_1
2021
john
5.5
1_2
2020
john
5.5
  1_3 
2021
jane
2.0     
  1_4 
2021
jane
2.0     
  1_5 
2019
garth
3.6     
  1_6 
2013
wayne
1.7     
I want to create a bar chart that gives me the total number of publications per year, so:
                                           x
                                           x
  x             x          x            x
2013    2019    2020     2021
My struggle is getting the count or aggregate of the count correct.
I’m also trying to crate an aggregate count by authors, so output would look like:
Author
Number of publications
John  
         2           
Jane 
         2           
Wayne 
         1           
Garth 
         1           
Thanks for help or advice!
Both of these aggregations should use a single dimension and a single measure. For both, the measure should be a simple count:
view: my_view {
measure: number_of_publications {
type: count
}
}
Then in the explore, you should only select this measure and a single dimension (year for the first one and Author for the second), and you'll end up with a table like the one you posted above for Author.
Once you have the table, just select the bar chart type and you should be good to go.

How to join SQL query in sqlite?

How can I write second query instead of 'users_statistic' in first query?
SELECT *
from 'users' LEFT JOIN 'users_statistic'
ON users.id=users_statistic.user_id
SELECT *, SUM(clicks) as sum_clicks, SUM(page_views) as sum_page_views
FROM 'users_statistic'
GROUP BY user_id
Second query return table
user_id    sum_clicks       sum_page_clicks
1                 754                         543
2                 234                          987
In table 'users' is field id, which equivalent user_id in table 'users_statistic'. Also there are no fields sum_clicks and sum_page_clicks in table 'users'. I want to add fields sum_clicks and sum_page_clicks from second query to table 'users'
You can do the aggregation directly in the 1st query:
SELECT u.id, u.name,
COALESCE(SUM(s.clicks), 0) sum_clicks,
COALESCE(SUM(s.page_views), 0) sum_page_views
FROM users u LEFT JOIN users_statistic s
ON u.id = s.user_id
GROUP BY u.id
I use COALESCE() so that you get 0 instead of null if for a user there are no clicks or page views.

Msg 207, Level 16, State 1, Line 1 Invalid column name 'ItemTotal' [closed]

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 1 year ago.
Improve this question
I wrote this code. It works fine without my WHERE Statement. I keep getting an error
Msg 207, Level 16, State 1, Line 1 Invalid column name 'ItemTotal'.
I don't know what I did wrong!
SELECT    
    ItemID, 
    ItemPrice,    
    ItemPrice * quantity AS PriceTotal,
    DiscountAmount * quantity AS DiscountTotal,
    ((ItemPrice - DiscountAmount) * quantity) AS ItemTotal
FROM                                                                                                                                                               
    OrderItems
WHERE ItemTotal > 500;
No database platform was given, but based on the query: 'ItemTotal' is not a column you can use, as it's an alias. You need to filter on the actual data
SELECT
ItemID,
ItemPrice,
ItemPrice * quantity AS PriceTotal,
DiscountAmount * quantity AS DiscountTotal,
((ItemPrice - DiscountAmount) * quantity) AS ItemTotal
FROM
OrderItems
WHERE ((ItemPrice - DiscountAmount) * quantity) > 500;

Moqui ::: How to edit list using section iterator

We are trying to display data in a form-list field using section-iterate. Data is being displayed correctly. However, once updating fields, the list used in the section-iterator is not being updated.
Sample code:
<form-single name=“editTest”  transition=“editOneTest”>
<auto-fields-entity entity-name="test.Test” field-type="edit"/>
<field name="testDetails"><default-field>
<section-iterate name="TestDetailSection" list="testDetailList" entry="testDetail" >
        <condition>
            <compare field="testDetail.testId" operator="equals" to-field="testId"/>
        </condition>
        <widgets>
            <field name="hours">
                <default-field>
                    <text-find default-operator="equals" hide-options="true" default-value="${testDetail.hours}" size="5" />
                </default-field>
            </field>
        </widgets>
    </section-iterate>
</default-field></field>
</form-single>
Notes:
We tried to declare list like and add the hours edited in the new list. It didn't work.
I tried to create a script inside of section-iterate to edit the testDetailList and didn't work.
Kindly, assit us to solve this issue.
Make sure you have the XSD (xml-screen-.xsd in this case) specified in your screen XML file and that your editor is validating the XML. The XML you've mentioned here is not valid.
The 'field' element cannot contain another field element, and a field element can't go under the 'widgets' element (it can only go under a default-field, conditional-field, or header-field element).
If you look at the HTML generated you'll see it has issues as the macros to transform XML to HTML do not support this sort of thing.

Repeating rows based on column value in each row

I've this table with the following data
Job  Quantity Status Repeat 
1    100      OK     2 
2    400      HOLD   0 
3    200      HOLD   1 
4    450      OK     3 
Based on the value in the Repeat column for each row, the row should be repeated again. For example for the Job 1, Repeat value is 2 so the Job 1 should repeat two more times.
The resultant table should be as below
Job    Quantity Status Repeat 
1      100       OK     2 
1      100       OK     2 
1      100       OK     2 
2      400       HOLD   0 
3      200       HOLD   1 
3      200       HOLD   1 
4      450       OK     3 
4      450       OK     3 
4      450       OK     3 
4      450       OK     3 
Can someone please help me out with this query?
am using oracle 10g
You could use a recursive CTE:
with cte(Job, Repeat, i) as
(
select Job
, Repeat
, 0
from YourTable
union all
select Job
, Repeat
, i + 1
from cte
where cte.i < cte.Repeat
)
select *
from cte
order by
Job
, i
Live example at SQL Fiddle.
Supposing you won't generate more than 1000 rows per row:
with num as (select level as rnk from dual connect by level<=1000)
select Job, Quantity, Status, Repeat, rnk
from t join num on ( num.rnk <= repeat )
order by job, rnk;
Here is a test:
http://sqlfiddle.com/#!4/4519f/12
UPDATE: As Jeffrey Kemp said, you can "detect" the maximum with a subquery:
with num as (select level as rnk
from dual
connect by level<=(select max(repeat) from t)
)
select job, quantity, status, repeat, rnk
from t join num on ( num.rnk <= repeat )
order by job, rnk;
Instead of doing this manipulation with query you can get this data first in a data table and add rows to a new data table based on the value of repeat and then bind this new data table.