Sample code:
UPDATE
TEMP_TABLE_NTI_D_test1 TEMP_NTID
SET
TEMP_NTID.WEEKLY_FLAG='Y',
TEMP_NTID.PROGRAM_COUNT=0,
FROM
(
SELECT
*
FROM
(
SELECT
st_date,
NET_CODE,
PR_CODE,
ST_HR,
ST_MIN,
sId,
DURATION,
REC_FLAG,
ROW_NUMBER() OVER(PARTITION BY NET_CODE,PR_CODE,
REC_FLAG,st_date,sId
ORDER BY ST_HR,ST_MIN) ROW_NUM
FROM
TEMP_TABLE_NTI_D_test1
WHERE
BRK_IND = 0
AND GAP_IND = 'Y'
AND COM_IND != 'Y' ) AB
WHERE
ROW_NUM > 1) TEMP_TABLE_GAPPED_ZEROES
WHERE
TEMP_NTID.NET_CODE = TEMP_TABLE_GAPPED_ZEROES.NET_CODE
AND TEMP_NTID.PR_CODE = TEMP_TABLE_GAPPED_ZEROES.PR_CODE
AND TEMP_NTID.ST_HR = TEMP_TABLE_GAPPED_ZEROES.ST_HR
AND TEMP_NTID.ST_MIN = TEMP_TABLE_GAPPED_ZEROES.ST_MIN
AND TEMP_NTID.DURATION = TEMP_TABLE_GAPPED_ZEROES.DURATION
AND TEMP_NTID.REC_FLAG = TEMP_TABLE_GAPPED_ZEROES.REC_FLAG
AND TEMP_NTID.st_date = TEMP_TABLE_GAPPED_ZEROES.st_date
;
Instead of updating the column I would like to receive a SELECT statement that gives a readout of each row (that would be updated if it was an UPDATE statement).
This is the most straightforward translation from the update.
select
TEMP_NTID.* --Select the table's records instead of update.
FROM
(
SELECT
*
FROM
(
SELECT
st_date,
NET_CODE,
PR_CODE,
ST_HR,
ST_MIN,
sId,
DURATION,
REC_FLAG,
ROW_NUMBER() OVER(PARTITION BY NET_CODE,PR_CODE,
REC_FLAG,st_date,sId
ORDER BY ST_HR,ST_MIN) ROW_NUM
FROM
TEMP_TABLE_NTI_D_test1
WHERE
BRK_IND = 0
AND GAP_IND = 'Y'
AND COM_IND != 'Y' ) AB
WHERE
ROW_NUM > 1) TEMP_TABLE_GAPPED_ZEROES
,TEMP_TABLE_NTI_D_test1 TEMP_NTID --Move the updated table here.
WHERE
TEMP_NTID.NET_CODE = TEMP_TABLE_GAPPED_ZEROES.NET_CODE
AND TEMP_NTID.PR_CODE = TEMP_TABLE_GAPPED_ZEROES.PR_CODE
AND TEMP_NTID.ST_HR = TEMP_TABLE_GAPPED_ZEROES.ST_HR
AND TEMP_NTID.ST_MIN = TEMP_TABLE_GAPPED_ZEROES.ST_MIN
AND TEMP_NTID.DURATION = TEMP_TABLE_GAPPED_ZEROES.DURATION
AND TEMP_NTID.REC_FLAG = TEMP_TABLE_GAPPED_ZEROES.REC_FLAG
AND TEMP_NTID.st_date = TEMP_TABLE_GAPPED_ZEROES.st_date
;
Related
I am removing a user function which finds shows item prices based on configurations but the function is too slow.
Therefore I'm trying to write a query to do the same. This query finds the latest price that matches the required criteria
This is kind of what I'm going for but I cannot figure out how to handle this requirement correctly:
(Intellisesnse says s.inventdimid does not exist in the h subquery)
SELECT s.salesid
,s.itemid
,h.price
FROM salesline s
LEFT OUTER JOIN (
SELECT TOP 1 p.price
,p.itemid
,p.dataareaid
,l.inventdimid
FROM inventitemprice p
JOIN inventdim d ON d.dataareaid = p.dataareaid
AND d.inventdimid = p.inventdimid
JOIN inventdim l ON l.dataareaid = p.dataareaid
AND (
l.configid = d.configid
OR d.configid = ''
)
AND (
l.inventcolorid = d.inventcolorid
OR d.inventcolorid = ''
)
AND (
l.inventsizeid = d.inventsizeid
OR d.inventsizeid = ''
)
AND (
l.inventstyleid = d.inventstyleid
OR d.inventstyleid = ''
)
AND (p.ACTIVATIONDATE < getdate())
AND l.inventsiteid = d.inventsiteid
WHERE pricetype = 0
AND l.inventdimid = s.inventdimid /* <========= */
AND p.dataareaid = 'lkc'
ORDER BY activationdate DESC
,d.configid DESC
,d.inventcolorid DESC
,d.INVENTSIZEID DESC
,d.inventstyleid DESC
) AS h ON h.itemid = s.itemid
AND h.DATAAREAID = s.DATAAREAID
AND h.INVENTDIMID = s.inventdimid
WHERE s.dataareaid = 'lkc'
AND s.SALESSTATUS = 1
What would be the appropriate method for querying this?
I'm obviously new to this and I need some help. I have this code in SQL Server Management Studio.
The error that I get is
Msg 156, Level 15, State 1, Line 38
Incorrect syntax near the keyword 'IF'
If I execute direct select statement instead of using "If" the query is successfully executed.
Please point out what I am missing and where is my mistake.
Thanks a lot.
declare #dateFrom [date] = cast(dateadd(day, -7, getdate()) as [date]);
declare #dateTo [date] = cast(dateadd(day, 28, getdate()) as [date]);
declare #prTypeCode [varchar](10) = null;
declare #ExcludeA [bit] = 0 ;
declare #ExcludeB [bit] = 0;
;with distribution as
(
select *
from [schema1].[Table1]
),
product as
(
select *
from [schema1].[Product]
),
fint as
(
select
*,
(case when CHARINDEX('0%', FIN_ CODE) > 0 then 1 else 0 end) as ZFlag
from [schema1].[FinTab]
),
deal as
(
select
*,
case when (AG_ID = 5 or DE_ID = 6) then 1
else 0 end as Ex_flag
from
[P_ BASE1].[ schema2].[table3]
),
dealersn as
(
select distinct *
from [P_ BASE1].[ schema2].[table4]
),
regionN as
(
select distinct *
from [P_ BASE1].[ schema2].[table5]
),
final as
(
select
d.PRODUCT_CODE, p.PR_NAME, p.PR_TYPE_CODE, p.PR_ACTIVE,
d.FIN_TABLE_CODE, ft.FT_NAME, ft.FT_ACTIVE,
cast(d.SND_TO_DATE as [date]) as SND_TO_DATE,
count(d.SN_ID) as SHOP_COUNT,
min(ft.ZFlag) as ZFlag,
min(ds.Ex_flag) as ExFlag, dn.SND_FULLNAME,rn.REG_NAME
from
distribution d
left outer join
product p on p.PRODUCT_CODE = d.PRODUCT_CODE
left outer join
fint ft on ft. FIN_ CODE = FIN_ CODE
left outer join
deal as ds On d.SN_ID = ds.SHOP_ID
left outer join
dealersn as dn on d.SN_ID = dn.SN_DATA_ID
left outer join
regionN as rn ON ds.REGION_ID = rn.REGION_ID
where
d.SND_TO_DATE between #dateFrom and #dateTo
and (#prTypeCode is null or p.PR_TYPE_CODE = #prTypeCode)
group by
rn.REG_NAME, ds.REGION_ID, ds.SHOP_ID, d.PRODUCT_CODE, p.PR_NAME,
p.PR_TYPE_CODE, p.PR_ACTIVE, d.FIN_TABLE_CODE, ft.FT_NAME,
ft.FT_ACTIVE, d.SND_TO_DATE,dn.SND_FULLNAME
)
IF (#ZeroPercent = 0 AND #LargeChainsOrTushev = 0)
BEGIN
SELECT DISTINCT *
FROM final
WHERE ZFlag = 0 AND ExFlag = 0
END
ELSE
IF #ZeroPercent = 1 AND #LargeChainsOrTushev = 0
BEGIN
SELECT DISTINCT *
FROM final
WHERE ZFlag = 1 AND ExFlag = 0
END
ELSE IF #ZeroPercent = 0 AND #LargeChainsOrTushev = 1
BEGIN
SELECT DISTINCT *
FROM final
WHERE ZFlag = 0 AND ExFlag = 1
END
ELSE
BEGIN
SELECT DISTINCT *
FROM final
END
You have a with statement that "defines" a bunch of tables, the last of which is called final. This is called a CTE (Common Table Expression). You can use CTEs for many reasons, but the important thing is, you have to use the CTE in a query. Instead you define the CTE and then...do nothing.
If you put a line like this:
select * from final
just after the CTE (before the IF), it will run.
I need some help mimicking a TFS query.
I have tried writing the following SQL query to do so but I am not able to get a matching population:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb.dbo.#LastRecord') IS NOT NULL DROP TABLE #LastRecord
SELECT System_Id
, LastUpdatedDateTime = MAX(LastUpdatedDateTime)
INTO #LastRecord
FROM [dimWorkItem]
GROUP BY System_Id
SELECT distinct ID = w.System_Id
--Cannot find Department
, Department = '?'
, w.TeamProjectSK
, RequestedByUser = w.Custom_RequestedBy
, Title = w.System_Title
, [Priority] = w.Microsoft_VSTS_Common_Priority
, Activity = w.Microsoft_VSTS_Common_Activity
, da.AreaPath
, [State] = w.System_State
, Reason = w.System_Reason
, ClosedDate = w.Microsoft_VSTS_Common_ClosedDate
, ActivatedDate = Microsoft_VSTS_Common_ActivatedDate
, DevHours = Custom_DevHours
, CreatedDate = w.System_CreatedDate
, AssignedTo = dp.Name
, [Week] = CASE WHEN (w.System_State = 'Active' OR Microsoft_VSTS_Common_ClosedDate >= dateadd(d,-7,CONVERT(Date,getdate(),1))) THEN 'Current'
WHEN (w.System_State = 'Active' OR Microsoft_VSTS_Common_ClosedDate >= dateadd(d,-14,CONVERT(Date,getdate(),1)) AND Microsoft_VSTS_Common_ClosedDate < dateadd(d,-7,CONVERT(Date,getdate(),1))) THEN 'Last'
ELSE 'Previous' END
, TSRNumber = Custom_TSRNumber
FROM
(Select * from (select *, rn = row_number() over(partition by w1.System_Id, w1.TeamProjectSK, w1.System_State order by w1.System_Rev desc)
from dbo.DimWorkItem w1) d where rn = 1) w
JOIN #LastRecord l ON w.System_Id = l.System_Id AND w.LastUpdatedDateTime = l.LastUpdatedDateTime
LEFT OUTER JOIN dbo.DimArea da ON w.AreaSK = da.AreaSK
LEFT OUTER JOIN DimPerson dp ON w.System_AssignedTo__PersonSK = dp.PersonSK
WHERE System_WorkItemType = 'Task'
AND da.AreaPath like '\LOS\Reporting%'
AND w.Microsoft_VSTS_Common_Priority < 4
Also if anyone knows where I could find the department field as I am not sure whether it is a custom field or not.
SQL Server 2014: 12.0
TFS: 12.0
Visual studio professional 2015: 14.0
Thank you in advance for your suggestions!
I found a solution although still not able to find the the Department field :
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb.dbo.#LastRecord') IS NOT NULL DROP TABLE #LastRecord
SELECT System_Id, LastChangedDate = MAX(System_ChangedDate)
INTO #LastRecord
FROM [dimWorkItem]
GROUP BY System_Id
DECLARE #FromDateWeek DATE
DECLARE #FromDateTwoWeek DATE
SET #FromDateWeek = dateadd(d,-7,CONVERT(Date,getdate(),1))
SET #FromDateTwoWeek = dateadd(d,-14,CONVERT(Date,getdate(),1))
--SELECT #FromDate
SELECT ID = w.System_Id
--Cannot find Department
, Department = '?'
, w.TeamProjectSK
, RequestedByUser = w.Custom_RequestedBy
, Title = w.System_Title
, [Priority] = w.Microsoft_VSTS_Common_Priority
, Activity = w.Microsoft_VSTS_Common_Activity
, da.AreaPath
, [State] = w.System_State
, Reason = w.System_Reason
, ClosedDate = w.Microsoft_VSTS_Common_ClosedDate
, ActivatedDate = Microsoft_VSTS_Common_ActivatedDate
, DevHours = Custom_DevHours
, CreatedDate = w.System_CreatedDate
, AssignedTo = dp.Name
, [Week] = CASE WHEN w.Microsoft_VSTS_Common_ClosedDate >= #FromDateWeek OR w.System_State = 'Active' THEN 'Current'
WHEN (w.Microsoft_VSTS_Common_ClosedDate >= #FromDateTwoWeek AND w.Microsoft_VSTS_Common_ClosedDate < #FromDateWeek)
OR w.Microsoft_VSTS_Common_ClosedDate < #FromDateWeek THEN 'Last'
ELSE 'Previous' END
FROM [dimWorkItem] w
JOIN #LastRecord l ON w.System_Id = l.System_Id AND w.System_ChangedDate = l.LastChangedDate
LEFT OUTER JOIN DimPerson dp ON w.System_AssignedTo__PersonSK = dp.PersonSK
LEFT OUTER JOIN dbo.DimArea da ON w.AreaSK = da.AreaSK
WHERE
da.AreaPath LIKE '\LOS\Reporting%'
AND System_WorkItemType = 'Task'
AND (Microsoft_VSTS_Common_ClosedDate >= #FromDateTwoWeek
OR w.System_State = 'Active')
AND ISNULL(Microsoft_VSTS_Common_Priority,0) < 4
AND w.System_Reason <> 'Obsolete'
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
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