Update a column in the same query as it is to be made in? - sql

In SQL Server, I am trying to create a temp table then join based on the unique index key criteria set forth, organizing them based on their system numbers, it looks a little something like this:
SELECT DISTINCT
t1.[SysNr] AS [oldSysNr], t1.[SysNr] AS [newSysNr],
t1.[Year], t1.[WorkTm], t1.[AMSTC],
t1.[AJCC], t1.[ShifNum], t1.[FMN]
INTO
#TEMPTABLE
FROM
AppData.SCHED AS t1
JOIN
AppData.SCHED AS tS ON t1.ShifNum = tS.ShifNum
AND t1.WorkTM = tS.WorkTM
AND t1.FMN = tS.FMN
WHERE
t1.Year = 2019;
This will essentially give me the old records needed by the oldSysNr column as the year is the param I am looking at. However, I need to update the newSysNr column in the same query, no separate query to update. Is there any way that this can be achieved? I only know of doing update as a separate query.
Here is the data that is produced from the query:
oldSysNr NewSysNr Year WorkTm AMSTC AJJC SHIFNUM FMN
-----------------------------------------------------------
24 24 2019 3 WVB GH 9 YUBMS
25 25 2019 3 BMS MJ 8 YUBMS
26 26 2019 3 BMS PP 8 MJUNL
27 27 2019 4 ZMG MJ 5 MJUNL
28 28 2019 5 BR OP 3 COLHP
Here are the results that are desired:
oldSysNr NewSysNr Year WorkTm AMSTC AJJC SHIFNUM FMN
-----------------------------------------------------------
24 57 2019 3 WVB GH 9 YUBMS
25 58 2019 3 BMS MJ 8 YUBMS
26 59 2019 3 BMS PP 8 MJUNL
27 60 2019 4 ZMG MJ 5 MJUNL
28 61 2019 5 BR OP 3 COLHP
As mentioned, the param it is looking at is the year, and given that, the entire idea is that it would update NewSysNr provided that it was given the same join statement but it would be another year like 2020. Help in any given way on this issue is greatly appreciated.

You should be able to nest a subquery in the FROM clause. In other words, instead of selecting columns x,y,z from the table itself, you can replace the table name with a query which uses an updated WHERE clause.
So in this case it would look something like this: (Note: you may need to adjust the aliasing in the subquery...I'm just lazy. Also, you don't need to select all the columns in the subquery. The query in parenthesis is the subquery)
SELECT DISTINCT
tS.[SysNr] AS [newSysNr], t1.[oldSysNr]
t1.[Year], t1.[WorkTm], t1.[AMSTC],
t1.[AJCC], t1.[ShifNum], t1.[FMN]
INTO
#TEMPTABLE
FROM
(SELECT DISTINCT
t1.[SysNr] AS [oldSysNr]
t1.[Year], t1.[WorkTm], t1.[AMSTC],
t1.[AJCC], t1.[ShifNum], t1.[FMN]
FROM
AppData.SCHED AS t1
JOIN
AppData.SCHED AS tS ON t1.ShifNum = tS.ShifNum
AND t1.WorkTM = tS.WorkTM
AND t1.FMN = tS.FMN
WHERE
t1.Year = 2018)
AS t1
JOIN
AppData.SCHED AS tS ON t1.ShifNum = tS.ShifNum
AND t1.WorkTM = tS.WorkTM
AND t1.FMN = tS.FMN
WHERE
t1.Year = 2019;

Related

need to get group by data using join/subQuery on multiple tables

I have table lookup with columns trackingId and string
trackingId
string
1
QQ
3
we
2
QQ
4
rt
.
..
.
..
.
..
select trackingId from lookup where string = 'QQ'
I need to use output of this query in table - content_item. content_item follow below
content_id
tracking_id
approval_status
date
101
1
AP
2014
102
1
PN
2016
103
3
PN
2015
104
4
AP
2018
105
2
RJ
2019
106
4
PN
2019
107
5
PN
2019
108
6
RJ
2019
...
.
..
....
I want to group this data by date
my output should be like
year
count
2014
1
2019
3
....
.
means in each group tracing ids should be unique.
(if one tracking id is counted in one group then it should not be counted in any other group)
Also data of tracking id 3 and 4 should not be counted (b'z I only want data for string QQ).
Please let me know if this is doable. any help will be appreciated...
JOIN the tables to get the 'QQ' content_items. Then GROUP BY and COUNT() the rows:
select c.date, count(*)
from content_item c
join lookup l on c.tracking_id = l.tracking_id
where l.string = 'QQ'
group by c.date

SQL Server: inner join running total

I'm doing some work on a SQL Server 2008 database (before partition) and trying to get my head running totals using inner joins. I've followed a few online tutorials but I can't get the desired results.
This is the underlying data...
Compdate count
------------------
2 198
3 29
4 22
5 27
6 31
9 18
10 16
11 22
12 26
etc...
and I need to add a running total column.
This is the query I've created so far...
select
t1.Compdate,
t1.count,
Sum(t2.count) as 'Total'
from
DB_KpiTr_Remo_CumComp_TV t1
inner join
(select count, compdate
from DB_KpiTr_Remo_CumComp_TV
where Month like 'l%') t2 on t1.Count >= t2.Count
and t1.Compdate = t2.Compdate
where
t1.Month like 'l%'
group by
t1.Compdate, t1.count
order by
t1.Compdate
select Compdate, count
from DB_KpiTr_Remo_CumComp_TV t1
But all I'm getting back is the exact same numbers in my total column...
Compdate count Total
-------------------------
2 198 198
3 29 29
4 22 22
etc...
I've tried several combinations of joins and I get several combinations of results but not the one I'm looking for - what am I missing here?
You can use apply:
select u.*, u2.running_count
from underlying u outer apply
(select sum(u2.count) as running_count
from underlying u2
where u2.compdate <= u.compdate
) u2

How do I recursively find all matching rows in a table?

I'm trying to wrangle an existing database without resorting to tricks. I need to query within a linking table to find all matching id's recursively.
I've tried a number of nested join queries, but I'm not a SQL expert. I'm a programmer and while I work with simple databases complex queries like this are a struggle for me.
My table looks like this:
------------------------
| child_id | parent_ id|
________________________
2 16
3 16
4 16
11 10
12 11
16 7
17 10
18 17
19 7
20 19
21 10
22 21
23 22
24 22
26 20
I only know the top-level parent id. I want to find all associated child ID's.
If the parent ID was 7, I need to return 16,19,2,3,4,20,26.
NOTE: This solution will work in MariaDB 10.2.2 and above.
Try Common Table Expression:
with recursive cte(child_id, parent_id) as (
select child_id, parent_id from MyTable
where parent_id = 7
union all
select mt.child_id, mt.parent_id from MyTable mt
inner join cte t on mt.parent_id = t.child_id
)
select * from cte;

SQL Server, joining all values in column with some values of another

I'm pretty bad at explaining, so I'll try and let my examples do most of the talking. Let's say I have a table like so:
dbo.ExampleTable
===================================
ID Year Data1 Data2
====== ======== ========= =========
12 2016 FOO BAR
13 2016 FOO MAN
14 2016 SAW BAR
20 2017 FOO BAR
21 2017 FOO MAN
27 2017 SAW BAR
29 2017 CHU CAR
44 9999 FOO BAR
48 9999 FOO MAN
51 9999 SAW BAR
52 9999 CHU CAR
Some notes:
ID is unique
(Year, Data1, Data2) is unique
The only values in the Year column will be 2016, 2017 or 9999
I want to create a table from that data that looks like this:
ID_9999 ID_2016 ID_2017
=========== =========== ===========
44 12 20
48 13 21
51 14 27
52 NULL 29
So essentially, for every unique pairing of Data1 and Data2 where Year=9999, I want to create a row which contains the ID of that pairing where Year=9999, as well as the ID for the pairings where Year=2016 and also Year=2017. Additionally, if either 2016 or 2017 do not containing that Data pairing, I want their value as NULL.
This is the query I've got so far:
SELECT tbl9999.ID ID_9999,
tbl2016.ID ID_2016,
tbl2017.ID ID_2017
FROM dbo.ExampleTable tbl9999
LEFT JOIN dbo.ExampleTable tbl2016
ON tbl9999.Data1 = tbl2016.Data1
AND tbl9999.Data2 = tbl2016.Data2
LEFT JOIN dbo.ExampleTable tbl2017
ON tbl9999.Data1 = tbl2017.Data1
AND tbl9999.Data2 = tbl2017.Data2
WHERE tbl9999.Year=9999
AND tbl2016.Year=2016
AND tbl2017.Year=2017
This seems to work mostly fine, however it will generate a table like this:
ID_9999 ID_2016 ID_2017
=========== =========== ===========
44 12 20
48 13 21
51 14 27
*Notice that it's missing the row with the null value in my example above. Is there any way to change my query to include that null value such that I have it in my example?
Please let me know if I'm missing any information or need anything clarified. Thanks in advance!
EDIT:
I was able to find an answer on my own! This is the code I used to achieve my desired result:
SELECT [9999] [ID_9999],
[2016] [ID_2016],
[2017] [ID_2017]
FROM dbo.ExampleTable
PIVOT (MAX([ID]) FOR [Year] IN ([2016],[2017],[9999])) [x]
ORDER BY ID_9999
You can do this in multiple ways. Conditional aggregation seems simple enough:
select max(case when year = 2016 then id end) as id_2016,
max(case when year = 2017 then id end) as id_2017,
max(case when year = 9999 then id end) as id_9999
from (select t.*, row_number() over (partition by year order by id) as seqnum
from dbo.ExampleTable t
) t
group by seqnum
order by seqnum;

How to fill in the gaps in a query of totals with zeroes?

I have a table with data like this
picks
20
20
20
18
17
12
12
9
9
This is the table but I need to get result like this.
Picks Count
20 3
19 0
18 1
17 1
16 0
...up to
1 12
How can we write query to get zero totals for data which doesn't exist in the table?
Arun
Use a subquery to generate all the numbers and then outer join it to your table.
with nos as ( select level as pick_id
from dual
connect by level <= 20 )
select nos.pick_id
, count(*)
from nos
left outer join picks
on nos.pick_id = picks.id
group by nos.pick_id
order by nos.pick_id desc ;