Adding results from two queries - sql-server

I'm using MS-SQL 2008 R2.
I have 2 Queries which are returning the required results.
But I need to add the two results from each queries to provide a final value [Enterprise Value]. I'm sure this is very straight forward but I'm going round in circles on this, have tried incorporating SUM which I think is the right approach?
Here is the full query as it currently stands:
declare #d1 datetime='2015-12-22'
(select
c.fs_perm_sec_id,
((c.p_price * s.p_com_shs_out)/1000) as [Enterprise Value]
from fp_v1.fp_basic_bd c
left join edm_v1.edm_security_entity_map e
on e.fs_perm_sec_id= c.fs_perm_sec_id
left join fp_v1.fp_basic_sho s
on s.fs_perm_sec_id = c.fs_perm_sec_id
and c.date=#d1
where s."date" =
(
select MAX(s2."date")
from fp_v1.fp_basic_sho s2
where s2.fs_perm_sec_id=c.fs_perm_sec_id
and s2."date" <= c."date"
)
and c."date"=#d1
and e.termination_date is null
and c.fs_perm_sec_id = 'GPHC8W-S-GB')
UNION ALL
select
ff.fs_perm_sec_id,
((FF_debt + ff_pfd_stk + ff_min_int_accum) - FF.ff_cash_st) as [Enterprise Value]
from ff_v2.ff_basic_af_v2 FF
where FF."date" =
( select MAX(FF2."date")
from ff_v2.ff_basic_af_v2 FF2
where FF2.fs_perm_sec_id=FF.fs_perm_sec_id
and FF.date <= FF2.date
)
and FF.fs_perm_sec_id =('GPHC8W-S-GB')
When inserting a "UNION ALL" between the two queries I get the following results:
fs_perm_sec_id Enterprise Value
GPHC8W-S-GB 9270.5204655
GPHC8W-S-GB 835
What I would like to achieve is a sum of the two values brought onto one row, i.e.:
fs_perm_sec_id Enterprise Value
GPHC8W-S-GB 10105.52
Thanks for your help.
Final SQL:
declare #d1 datetime='2015-12-23'
Select fs_perm_sec_id, SUM([Enterprise Value]) AS 'Enterprise Value'
from
(
(select
c.fs_perm_sec_id,
((c.p_price * s.p_com_shs_out)/1000) as [Enterprise Value]
from fp_v1.fp_basic_bd c
left join edm_v1.edm_security_entity_map e
on e.fs_perm_sec_id= c.fs_perm_sec_id
left join fp_v1.fp_basic_sho s
on s.fs_perm_sec_id = c.fs_perm_sec_id
and c.date=#d1
where s."date" =
(
select MAX(s2."date")
from fp_v1.fp_basic_sho s2
where s2.fs_perm_sec_id=c.fs_perm_sec_id
and s2."date" <= c."date"
)
and c."date"=#d1
and e.termination_date is null
and c.fs_perm_sec_id in ('FT9TC5-S-GB','GPHC8W-S-GB','R85KLC-S-US'))
UNION ALL
select
ff.fs_perm_sec_id,
((FF_debt + ff_pfd_stk + ff_min_int_accum) - FF.ff_cash_st) as [Enterprise Value]
from ff_v2.ff_basic_af_v2 FF
where FF."date" =
( select MAX(FF2."date")
from ff_v2.ff_basic_af_v2 FF2
where FF2.fs_perm_sec_id=FF.fs_perm_sec_id
and FF.date <= FF2.date
)
and FF.fs_perm_sec_id in ('FT9TC5-S-GB','GPHC8W-S-GB','R85KLC-S-US')) t
group by t.fs_perm_sec_id

just use the Derived Table and Group by
Select fs_perm_sec_id,
SUM(Enterprise Value) EnterpriseValue
from (**your whole code**)
GROUP BY fs_perm_sec_id

use group by
How to use group by with union in t-sql
SELECT id,sum(*)
FROM ( SELECT id,
time
FROM dbo.a
UNION
SELECT id,
time
FROM dbo.b
)
GROUP BY id

DECLARE
#d1 DATE = '20151222'
, #fs_perm_sec_id VARCHAR(100) = 'GPHC8W-S-GB'
SELECT #fs_perm_sec_id, SUM([Enterprise Value])
FROM (
SELECT [Enterprise Value]
FROM (
SELECT
c.fs_perm_sec_id
, (c.p_price * s.p_com_shs_out) / 1000 AS [Enterprise Value]
, RowNum = ROW_NUMBER() OVER (ORDER BY s.[date] DESC)
from fp_v1.fp_basic_bd c
join fp_v1.fp_basic_sho s on s.fs_perm_sec_id = c.fs_perm_sec_id
left join edm_v1.edm_security_entity_map e on e.fs_perm_sec_id= c.fs_perm_sec_id
where c.[date] = #d1
and e.termination_date is null
and c.fs_perm_sec_id = #fs_perm_sec_id
) t
WHERE t.RowNum = 1
UNION ALL
SELECT FF_debt + ff_pfd_stk + ff_min_int_accum - ff_cash_st
FROM (
SELECT
ff.fs_perm_sec_id
, FF_debt
, ff_pfd_stk
, ff_min_int_accum
, FF.ff_cash_st
, RowNum = ROW_NUMBER() OVER (ORDER BY FF.[date] DESC)
FROM ff_v2.ff_basic_af_v2 FF
WHERE FF.[date] =
AND FF.fs_perm_sec_id = #fs_perm_sec_id
) t
WHERE t.RowNum = 2
) t

Related

Select with WITH

I am new in MySQL I have a db2 select and a would like to do this in MSsql and with WITH clause
db2
1 SQL.
SELECT
SQLUSER.TT_VALUTRAZ.SIFRA3,
SQLUSER.TT_VALUTRAZ.SIFVAL32,
SQLUSER.TT_VALUTRAZ.DATUM,
SQLUSER.TT_VALUTRAZ.RAZMERJE
FROM
SQLUSER.TT_VALUTRAZ
WHERE
(
(SQLUSER.TT_VALUTRAZ.DATUM >= '1.5.2007')
) ---> this go to DW.TEMP_PFPC_TT_VALUTRAZ
2 sql.
SELECT
'705' AS SIFRA3,
'891' AS SIFVAL32,
A.DATUM,
A.RAZMERJE AS RAZMERJE
FROM
DW.TEMP_PFPC_TT_VALUTRAZ A
WHERE
A.DATUM >= '1.5.2007' AND
A.SIFRA3 = '891' AND
A.SIFVAL32 = '978' AND
('705', '891', A.DATUM) NOT IN
(
SELECT
SIFRA3,
SIFVAL32,
DATUM
FROM
DW.TEMP_PFPC_TT_VALUTRAZ
WHERE
SIFRA3 = '705' AND
SIFVAL32 = '891'
)
now I like to join this two SQL statement and would like to use ons with clause and MSsql syntax
There are many ways of doing this. I only posted one way. There are some places that have been changed due to syntax issues. Let me know this answer if this answer is useful.
; WITH CTE_1 AS ( SELECT
SQLUSER.TT_VALUTRAZ.SIFRA3,
SQLUSER.TT_VALUTRAZ.SIFVAL32,
SQLUSER.TT_VALUTRAZ.DATUM,
SQLUSER.TT_VALUTRAZ.RAZMERJE
FROM
SQLUSER.TT_VALUTRAZ
WHERE
(
(SQLUSER.TT_VALUTRAZ.DATUM >= '1.5.2007')
) ---> this go to DW.TEMP_PFPC_TT_VALUTRAZ
)
, CTE_2 AS (
SELECT * FROM
(
SELECT
'705' AS SIFRA3,
'891' AS SIFVAL32,
A.DATUM,
A.RAZMERJE AS RAZMERJE
FROM
DW.TEMP_PFPC_TT_VALUTRAZ A
) AS B
WHERE
B.DATUM >= '1.5.2007' AND
B.SIFRA3 = 891 AND
B.SIFVAL32 = 978 AND
B.SIFRA3 NOT IN (705) --use of sub queries in where clause has been fixed.
AND B.SIFVAL32 NOT IN (891) --use of sub queries in where clause has been fixed.
AND B.DATUM NOT IN
(
SELECT
DATUM
FROM
DW.TEMP_PFPC_TT_VALUTRAZ
)
)
SELECT * FROM
CTE_1 AS [C]
INNER JOIN CTE_2 AS [CT]
ON [CTE_1]. [SIFRA3] = [CT].[SIFRA3]
AND [C]. [SIFVAL32] = [CT].[SIFVAL32]
AND [C].[DATUM] = [CT].[DATUM]
AND [C].[RAZMERJE] = [CT].[RAZMERJE]

How will SQL Server execute this WITH clause

I have the following query. Here 'B' is giving me non repeated MessageIds and i am using them in subquery with A, B is internally using A.
So when i call SELECT in the last part, will it execute A again or will it use data already fetched while B was being called ?
WITH A as (
SELECT z.Name, ze.Inside, ze.MessageId, ze.DateTime
FROM ZoneStateEntries ze
INNER JOIN Zone z
ON ze.ZoneId = z.ZoneId
WHERE ze.ObjectId = 1324
AND (Inside = 1 OR Inside = 0)
AND ze.DateTime BETWEEN '2018-10-22 00:00:00' AND '2019-11-05 00:00:00'
),
B as (
SELECT a.MessageId
FROM A a
INNER JOIN A b
on a.MessageId = b.MessageId
GROUP BY a.MessageId
HAVING COUNT(a.MessageId) = 1
)
SELECT *
FROM A
WHERE MessageId IN (
SELECT *
FROM B
)
AND a.Inside = 1
ORDER BY DateTime DESC
The data here is huge and we can't afford to execute query A multiple times. Can we optimize it further?
A a INNER JOIN A b looks like unnecessary. You can use COUNT(DISTINCT MessageId) for getting unique messages.
WITH A as (
SELECT z.Name, ze.Inside, ze.MessageId, ze.DateTime
FROM ZoneStateEntries ze
INNER JOIN Zone z
ON ze.ZoneId = z.ZoneId
WHERE ze.ObjectId = 1324
AND (Inside = 1 OR Inside = 0)
AND ze.DateTime BETWEEN '2018-10-22 00:00:00' AND '2019-11-05 00:00:00'
)
SELECT *
FROM A
WHERE MessageId IN (
SELECT MessageId
FROM A
GROUP BY MessageId
HAVING COUNT(DISTINCT MessageId) = 1
)
AND a.Inside = 1
ORDER BY DateTime DESC

Exact Claim Count for each rows using pivot with join in SQL Server 2012

By executing the below SQL 2012 Query, I got the following output
declare
#ticketstatus nvarchar(20) = 'To Be Allocated'
SELECT m1.ClaimSource, m1.Insurance, n1.[Claim Count], n1.[Claim Value],
ISNULL(m1.[0-30],0) [0-30],
ISNULL(m1.[31-60],0) [31-60],
ISNULL(m1.[61-90],0) [61-90],
ISNULL(m1.[91-120],0) [91-120],
ISNULL(m1.[121-210],0) [121-210],
ISNULL(m1.[210++],0) [210++]
FROM (
SELECT *
FROM (
SELECT ClaimSource, Insurance, CurrentBalance _Count, AgeBucket
FROM ClaimMaster
) m
PIVOT (
COUNT(_Count)
FOR AgeBucket IN ([0-30],[31-60],[61-90],[91-120],[121-210],[210++])
) n
) m1
join
(SELECT Insurance, COUNT(Insurance) [Claim Count], SUM(CurrentBalance) [Claim Value] FROM ClaimMaster
WHERE (TicketStatus = #ticketstatus OR #ticketstatus IS NULL)
GROUP BY Insurance) n1
ON m1.Insurance = n1.Insurance
ORDER BY n1.[Claim Count] DESC
How can I get the correct output for Claim Count, Claim Value on the 4, 5 & 6 rows. Instead of showing full claim count, it should show the respective claim count filter by Claim Source such as Claim Count should be 2 and appropriate Claim Value.
Can anyone help me on this.
Add claimsource and join on that as well?
declare
#ticketstatus nvarchar(20) = 'To Be Allocated'
SELECT m1.ClaimSource, m1.Insurance, n1.[Claim Count], n1.[Claim Value],
ISNULL(m1.[0-30],0) [0-30],
ISNULL(m1.[31-60],0) [31-60],
ISNULL(m1.[61-90],0) [61-90],
ISNULL(m1.[91-120],0) [91-120],
ISNULL(m1.[121-210],0) [121-210],
ISNULL(m1.[210++],0) [210++]
FROM (
SELECT *
FROM (
SELECT ClaimSource, Insurance, CurrentBalance _Count, AgeBucket
FROM ClaimMaster
) m
PIVOT (
COUNT(_Count)
FOR AgeBucket IN ([0-30],[31-60],[61-90],[91-120],[121-210],[210++])
) n
) m1
join
(SELECT ClaimSource, Insurance, COUNT(Insurance) [Claim Count], SUM(CurrentBalance) [Claim Value] FROM ClaimMaster
WHERE (TicketStatus = #ticketstatus OR #ticketstatus IS NULL)
GROUP BY ClaimSource, Insurance) n1
ON m1.Insurance = n1.Insurance and m1.ClaimSource = n1.ClaimSource
ORDER BY n1.[Claim Count] DESC

SQL Query Using WITH common_table_expression Fails in Codeigniter but Not SQL Studio

I created a query in MS SQL Management Studio for SQL Server 2012 that uses common_table_expression to self join a table. It works correctly in MS SQL Studio but in Codeigniter no result or error is returned.
The query:
WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY u.[PatientID], u.[CreateDate]) AS rn
FROM (
SELECT a.[PatientID], a.[BGValue], a.[CreateDate], a.[HospitalUnit], 'MSHA' as 'Hospital', h.[system_name], f.[facility_code], f.[facility_name], 'IV' as 'Treatment'
FROM [Analytics].[dbo].[MSHA_IVTreatment] a
JOIN [Analytics].[dbo].[MSHA_Patients] p
ON p.[PatientID] = a.[PatientID]
JOIN [Analytics].[dbo].[Facilities] f
ON f.[facility_code] = p.[facility_code]
JOIN [Analytics].[dbo].[Hospitals] h
ON f.[hospital] = h.[hospital]
WHERE a.[CreateDate] BETWEEN '2013-05-01' AND '2013-05-31'
UNION ALL
SELECT a.[PatientID], a.[BGValue], a.[CreateDate], a.[HospitalUnit], 'MSHA' as 'Hospital', h.[system_name], f.[facility_code], f.[facility_name], 'SubQ' as 'Treatment'
FROM [Analytics].[dbo].[MSHA_SubQTreatment] a
JOIN [Analytics].[dbo].[MSHA_Patients] p
ON p.[PatientID] = a.[PatientID]
JOIN [Analytics].[dbo].[Facilities] f
ON f.[facility_code] = p.[facility_code]
JOIN [Analytics].[dbo].[Hospitals] h
ON f.[hospital] = h.[hospital]
WHERE a.[CreateDate] BETWEEN '2013-05-01' AND '2013-05-31'
) u
)
SELECT mc.[PatientID], mc.[BGValue], mc.[CreateDate], mc.[Hospital], mc.[system_name] as 'System', mc.[facility_code], mc.[facility_name], mc.[HospitalUnit], DATEDIFF(second, mp.[CreateDate], mc.[CreateDate])/60 as 'Interval', mc.[Treatment]
FROM rows mc
JOIN rows mp
ON mc.rn = mp.rn + 1 and mc.[PatientID] = mp.[PatientID]
ORDER BY mc.[CreateDate] ASC;
When I put that into a variable and attempt to retrieve the result in codeigniter nothing is returned:
$result = $this->db->query($query);
CI_DB_sqlsrv_result Object
(
[conn_id] => Resource id #30
[result_id] => Resource id #41
[result_array] => Array
(
)
[result_object] => Array
(
)
[custom_result_object] => Array
(
)
[current_row] => 0
[num_rows] => -1
[row_data] =>
)
I have tried putting the query in a transaction but got the same result.
Any insight greatly appreciated.
Possible this be helpful for you -
;WITH [rows] AS
(
SELECT
a.[PatientID]
, a.[BGValue]
, a.[createdate]
, a.[HospitalUnit]
, Hospital = 'MSHA'
, h.[system_name]
, f.[facility_code]
, f.[facility_name]
, u.Treatment
, rn = ROW_NUMBER() OVER (ORDER BY u.[PatientID], u.[createdate])
FROM (
SELECT
PatientID
, BGValue
, createdate
, HospitalUnit
, Treatment = 'IV'
FROM dbo.MSHA_IVTreatment
WHERE createdate BETWEEN '20130501' AND '20130531'
UNION ALL
SELECT
PatientID
, BGValue
, createdate
, HospitalUnit
, Treatment = 'SubQ'
FROM dbo.MSHA_SubQTreatment
WHERE createdate BETWEEN '20130501' AND '20130531'
) a
JOIN [dbo].[MSHA_Patients] p ON p.[PatientID] = a.[PatientID]
JOIN [dbo].[Facilities] f ON f.[facility_code] = p.[facility_code]
JOIN [dbo].[Hospitals] h ON f.[Hospital] = h.[Hospital]
)
SELECT
mc.[PatientID]
, mc.[BGValue]
, mc.[createdate]
, mc.[Hospital]
, [System] = mc.[system_name]
, mc.[facility_code]
, mc.[facility_name]
, mc.[HospitalUnit]
, [Interval] = DATEDIFF(SECOND, mp.[createdate], mc.[createdate]) / 60
, mc.[Treatment]
FROM [rows] mc
JOIN [rows] mp ON mc.rn = mp.rn + 1 AND mc.[PatientID] = mp.[PatientID]
ORDER BY mc.[createdate];

how to convert the below subquery into joins using one update statement

Below is a complete query I have and the ultimate aim is to update the claim table. But it should be only one statement without any subquery, only joins are allowed because I am going to run this in an appliance which won't support subquery:
DECLARE #DecWdrwn as TABLE(CtryId smallint, CmId int, DecWdrwnDt int);
WITH s AS
(
SELECT
Ctryid,CmId,Dt,
ISNULL((
SELECT max(CmHistDtTmId)
FROM ClaimHistory l
WHERE St = 3
AND l.Ctryid = c.Ctryid
AND l.CmId = c.CmId)
, 0) MaxDec,
ISNULL((
SELECT max(CmHistDtTmId)
FROM ClaimHistory l
WHERE St = 7
AND l.Ctryid = c.Ctryid
AND l.CmId = c.CmId)
, 0) MaxSet
FROM
ClaimHistory c
WHERE
St =3
)
INSERT INTO #DecWdrwn
SELECT CtryId, CmId, Max(Dt) DecDt
FROM s
WHERE MaxSet > MaxDec
GROUP BY CtryId,CmId
Your response is much appreciated...
UPDATE Claims
SET CmDclnWdwnDt = (
SELECT DecWdrwnDt
FROM #DecWdrwn d
WHERE d.CmId = Claims.CmId
AND d.CtryId = Claims.CtryId
)
WHERE EXISTS (
SELECT *
FROM #DecWdrwn d
WHERE d.CmId = Claims.CmId
AND d.CtryId = Claims.CtryId
)
Please try INNER JOIN Update:
UPDATE a
SET a.CmDclnWdwnDt = b.DecWdrwnDt
FROM Claims a, #DecWdrwn b
WHERE a.CmId = b.CmId AND
a.CtryId =b.CtryId

Resources