SQL Random Item for each USER - sql

I have been searching and cannot find the right way to do this. In my query below, What I need is one random C.CREDENTIALING_K for each U.USER_K. I know the newid() will be needed somewhere, I just cannot find the proper place to put it.
select
U.USER_K,
U.FULLNAME as 'Chg_By',
CONVERT(DATE,AL.AUDITDATETIME) as 'Verif_Date',
P.ID,
P.LONGNAME,
CONVERT(DATE,P.DATEOFBIRTH) as 'DOB',
C.entity_k,
R.DESCRIPTION as 'CVI_TYPE',
C.CREDENTIALING_K,
CG.GROUPDESCRIPTION,
C.APPLICATION_RECEIVED,
R1.DESCRIPTION as 'Cur_STATUS',
CONVERT(DATE,C.USERDEF_D3) as 'MSO_DUE_DT'
from
VisualCACTUS.AUDITLOG AL
JOIN VisualCACTUS.USERS U
on U.user_k = AL.USER_K
join VisualCACTUS.CREDENTIALING C
JOIN VisualCACTUS.PROVIDERS P
on P.provider_k = C.PROVIDER_K
JOIN visualcactus.CREDENTIALINGGROUP CG
on CG.CREDENTIALINGGROUP_K = C.CREDENTIALINGGROUP_K
JOIN VisualCACTUS.REFTABLE R
on R.reftable_k = CG.TYPE_RTK
JOIN VisualCACTUS.REFTABLE R1
ON R1.REFTABLE_K = C.CREDENTIALINGSTATUS_RTK
--JOIN VisualCACTUS.CREDENTIALINGASSIGNMENTS CA
--on CA.credentialing_k = CA.credentialing_k
on C.CREDENTIALING_K = AL.FILE_PRIMARYKEY
where
AUDITLOG_K in (select AUDITLOG_K from VisualCACTUS.AUDITLOG_RECORDLEVEL where TABLE_NAME = 'CREDENTIALING '
and
AUDITLOG_RECORDLEVEL_K in (SELECT AUDITLOG_RECORDLEVEL_K from VisualCACTUS.AUDITLOG_FIELDLEVEL where NEWVALUE_SHORT = 'D2680X38F3'))
and
C.USERDEF_L1 = 0
and
CG.TYPE_RTK NOT IN ('D2870MPPSO','D2LC0YR0AR','D2DD1EIY5X')
and
CG.TYPE_RTK NOT LIKE ('SSP%')
and
C.credentialing_k not in (select credentialing_k from VisualCACTUS.CREDENTIALINGASSIGNMENTS where EA_K in (select ea_k from visualcactus.entityassignments where entity_k in ('HCA0000039',
'HCA0000040',
'HCA0000041',
'HCA0000043',
'HCA0000096',
'HCA0000095',
'HCA0000337',
'HCA0000903',
'HCA0000904',
'HCA0000905',
'HCA0000906',
'HCA0000080')))
and
CONVERT(DATE, AUDITDATETIME) = DATEADD(day, -1, convert(date, GETDATE()))
order by 'Chg_By'

Make a correlated subquery to return random CREDENTIALING_K
CREDENTIALING_K=(select top 1 C1.CREDENTIALING_K
from VisualCACTUS.CREDENTIALING c1
Where P.provider_k = C1.PROVIDER_K
order by newid())
Note : If needed add the filter that you have used for VisualCACTUS.CREDENTIALING table inside subquery too

Related

SQL Server aggregate function without group by

I want to include tcon.Inductive_Injection_Hours, tcon.Capacitive_Injection_Hours without applying group by. How can I do that?
SELECT
bp.Serial_Number,
tcon.Serial_Number AS ConverterSerialNumber,
MAX(tcon.Time_Stamp) AS DateStamp,
tcon.Inductive_Injection_Hours,
tcon.Capacitive_Injection_Hours
FROM
dbo.Bypass AS bp
INNER JOIN
dbo.Converter AS c ON bp.Bypass_ID = c.Bypass_ID
INNER JOIN
dbo.Converter_Tel_Data AS tcon ON c.Converter_ID = tcon.Converter_ID
WHERE
(bp.Site_ID = 7)
GROUP BY
bp.Serial_Number, tcon.Serial_Number,
tcon.Inductive_Injection_Hours, tcon.Capacitive_Injection_Hours
ORDER BY
ConverterSerialNumber
I have figured it out.
select [data].Serial_Number,Time_Stamp,Inductive_Injection_Hours,Capacitive_Injection_Hours,b.Serial_Number from Converter_Tel_Data as [data]
inner join dbo.Converter AS c On [data].Converter_ID = c.Converter_ID
inner join dbo.Bypass as b on c.Bypass_ID = b.Bypass_ID
WHERE
(Time_Stamp = (SELECT MAX(Time_Stamp) FROM Converter_Tel_Data WHERE Converter_ID = [data].Converter_ID)) And ([data].Site_ID=7)
ORDER BY [data].Serial_Number
You can use row_number - either in a CTE/derived table or using a trick with TOP 1.
Select Top 1 With Ties
bp.Serial_Number
, tcon.Serial_Number AS ConverterSerialNumber
, tcon.Time_Stamp AS DateStamp
, tcon.Inductive_Injection_Hours
, tcon.Capacitive_Injection_Hours
From dbo.Bypass AS bp
Inner Join dbo.Converter AS c On bp.Bypass_ID = c.Bypass_ID
Inner Join dbo.Converter_Tel_Data AS tcon ON c.Converter_ID = tcon.Converter_ID
Where bp.Site_ID = 7
Order By
row_number() over(Partition By bp.Serial_Number Order By tcon.Time_Stamp desc)
This should return the latest row from the tconn table for each bp.Serial_Number.

update with subquery

The code :
UPDATE tt_t_documents
SET t_Doc_header_ID = (SELECT
MIN(dh.Doc_header_ID)
FROM tt_t_documents td WITH (NOLOCK)
JOIN Doc_header dh WITH (NOLOCK)
ON dh.DH_doc_number = td.t_dh_doc_number
AND dh.DH_sub = 1
JOIN Pred_entry pe WITH (NOLOCK)
ON pe.Pred_entry_ID = dh.DH_pred_entry
JOIN Doc_type dt WITH (NOLOCK)
ON dty.Doc_type_ID = pe.PD_doc_type
AND dt.DT_mode = 5
HAVING COUNT(dh.Doc_header_ID) = 1);
I want to update my columns, but before that I also want to check if there is only one ID found.
The problem in this select is that I get more than one ID.
How can I write a query that updates each row and checks in the same query that there is only one id found?
I am guessing that you intend something like this:
update td
set t_Doc_header_ID = min_Doc_header_ID
from tt_t_documents td join
(select DH_doc_number, min(dh.Doc_header_ID) as min_Doc_header_ID
from Doc_header dh join
Pred_entry pe
on pe.Pred_entry_ID = dh.DH_pred_entry join
Doc_type dt
on dty.Doc_type_ID = pe.PD_doc_type and dt.DT_mode = 5
where dh.DH_doc_number = td.t_dh_doc_number and dh.DH_sub = 1
group by DH_doc_number
having count(dh.Doc_header_ID) = 1
) dh
on dh.DH_doc_number = td.t_dh_doc_number;
Using a join also means that you do not update the values where the condition does not match. If you use a left join, then the values will be updated to NULL (if that is your intention).
I'm not sure I believe you are getting more than one id back with that select given that you are doing a 'min' on it and have no group by. It should be only returning the lowest value for Doc_header_id.
To do what you are asking, first, you should have some way of joining to the tt_t_documents table in the update statement (eg. where td.id == tt_t_documents.id).
Second, you could re-write it to use the sub-query in the from. Something like:
update
tt_t_documents
set
t_Doc_header_ID = x.Doc_Header_id
from tt_t_documents join (
select td.id,
min(dh.Doc_header_ID)
from
tt_t_documents td
join Doc_header dh
on dh.DH_doc_number = td.t_dh_doc_number
and dh.DH_sub = 1
join Pred_entry pe
on pe.Pred_entry_ID = dh.DH_pred_entry
join Doc_type dt
on dty.Doc_type_ID = pe.PD_doc_type
and dt.DT_mode = 5
group by td.id
having
count(dh.Doc_header_ID) = 1
) x on tt_t_documents.id= x.id;
The syntax may not be perfect and I'm not sure how you want to find the doc_header_id but it would be something like this. The sub query would only return values with 1 doc_header_id). Not knowing the schema of your tables, this is as close as I can get.

SQL query - having expression > 0

I am working on Microsoft SQL Server 2014 and I have the following SQL query which works:
SELECT
h.entidade, h.datadoc, h.tipodoc, h.numdoc,
(SELECT valortotal -
(SELECT COALESCE(SUM(l.valorrec), 0)
FROM LinhasLiq as l
INNER JOIN cabliq ON l.IdCabLiq = CabLiq.id
INNER JOIN Historico ON L.IdHistorico = Historico.id
WHERE cabliq.DataDoc < '01/05/2015'
AND historico.id = h.id)) as 'valor pendente',
coalesce(documentosCCT.Descricao,'')
+' '+ CASE WHEN h.modulo<>'V' THEN coalesce(documentosVenda.Descricao,'') else'' END
+' '+ coalesce(h.descricao,'') AS descricaogeral
FROM
Historico h
LEFT JOIN
documentosCCT ON h.TipoDoc = documentosCCT.Documento
LEFT JOIN
documentosVenda ON h.Tipodoc = documentosVenda.Documento
WHERE
h.entidade = 'ta0141' AND
(h.tipoentidade = 'C' OR h.tipoentidade = 'F')
ORDER BY
datadoc ASC
and this specific expression
(select valortotal - (SELECT COALESCE(SUM(l.valorrec),0) from LinhasLiq as l
inner join cabliq on l.IdCabLiq = CabLiq.id
inner join Historico on L.IdHistorico = Historico.id
where cabliq.DataDoc < '01/05/2015' and historico.id = h.id)) as 'valor pendente'
returns a lot of 0 values, so how can I put this entire expression in a having X > 0 clause, or any other way as long as the rows with this expression = 0 doesn't show?
Many thanks.
i don't know what is your circumstances if it is feasible try to make query in single select statement instead of multiple
Don't make an alias valor pendente like that should be valorpendente
Now you can use CTE
;WITH CTE AS
(
-- YOUR QUERY
)
SELECT * FROM CTE
WHERE valorpendente > 0

Query to return all values in a specific table column

The query below returns a somatory of all groups in the year.
How can I return all groups that exists in IND_GRUPO but grouped by the month, if doesn't exist the group for the current month, the name should appear, but the somatory will be 0. All joins should be kept.
SELECT SUM(p.valor), c.nm_grupo, c.cd_grupo, YEAR(p.dt_emissao)
FROM ind_receita p
JOIN ind_equipto o ON p.cd_equipto = o.cd_equipto
JOIN ind_grupo c ON o.cd_grupo = c.cd_grupo
WHERE YEAR(p.dt_emissao) = YEAR(GETDATE())
GROUP BY YEAR(p.dt_emissao), c.nm_grupo, c.cd_grupo
ORDER BY 1 DESC
Try this:
SELECT c.nm_grupo, c.cd_grupo, YEAR(GETDATE()),
(SELECT SUM(p.valor)
FROM ind_receita p
JOIN ind_equipto o ON p.cd_equipto = o.cd_equipto
JOIN ind_grupo c2 ON o.cd_grupo = c2.cd_grupo
WHERE c2.cd_grupo = c.cd_grupo
AND YEAR(p.dt_emissao) = YEAR(GETDATE())) AS valor
FROM ind_grupo c

Combine SELECT statements. Help Needed

I have the following two T-SQL statements that I really need to combine:
SELECT Aircraft.Id AS AircraftID, AircraftManufacturers.Name, AircraftModels.ModelName,
Aircraft.ModelSuffix, Aircraft.ImageFileName, Aircraft.Year, Aircraft.SerialNo,
Locations.DescriptionForSite, Aircraft.Description, Aircraft.Description2,
Aircraft.InfoWebAddress, Aircraft.ImageDescription, Advertisers.Id AS AdvertisersID,
Advertisers.Name AS AdvertisersName, Aircraft.AircraftDataId, Aircraft.ForSale, Aircraft.ForLease,
Aircraft.TTAF, Aircraft.ReSend, Aircraft.ReSendReason, Aircraft.Registration, Aircraft.AdType,
Aircraft.HasAlternateImage, Aircraft.AlternateImageDescription,
Aircraft.Price, AircraftModels.AircraftType, Advertisers.CurrentEMagLink, Aircraft.CurrentEMagLink,
Aircraft.Email, Aircraft.IsSold, Aircraft.SoldDate, Aircraft.DateAdded, Aircraft.ExtendedDetails,
Aircraft.LastUpdateDate, Aircraft.ImageCount, Aircraft.ContactTelephone, AircraftModels.id, Advertisers.IsPremiumAdvertiser,
Aircraft.Location, Advertisers.ContactTelephone As AdvertisersTelephone, Aircraft.LastUpdateDate, Aircraft.EndDate, Aircraft.VideoLink
FROM (((Aircraft
INNER JOIN Advertisers ON Aircraft.AdvertiserId = Advertisers.Id)
INNER JOIN AircraftModels ON Aircraft.AircraftModelId = AircraftModels.Id)
INNER JOIN AircraftManufacturers ON AircraftModels.ManufacturerId = AircraftManufacturers.Id)
INNER JOIN Locations ON Aircraft.LocationId = Locations.Id
JOIN iter$simple_intlist_to_tbl(#ids) i ON AircraftModels.id = i.number
WHERE (Aircraft.IsActive=1 AND Advertisers.IsActive=1 AND (Aircraft.EndDate>=#Date OR Aircraft.EndDate Is Null) AND Locations.DescriptionForSite LIKE #Location)
OR (Advertisers.IsActive=1 AND Aircraft.IsSold=1 AND Aircraft.SoldDate>=#Date2 AND Locations.DescriptionForSite LIKE #Location)
ORDER BY Advertisers.IsPremiumAdvertiser ASC, Aircraft.DateAdded DESC, Aircraft.ListPosition DESC,
Aircraft.LastUpdateDate, AircraftManufacturers.Name, AircraftModels.ModelName, Aircraft.ModelSuffix,
Aircraft.Id DESC
and
SELECT TOP (1) dbo.Addresses.Email, dbo.Addresses.Contact, dbo.Addresses.Telephone1
FROM dbo.AdvertiserAddressLink
INNER JOIN dbo.Addresses ON dbo.AdvertiserAddressLink.AddressId = dbo.Addresses.Id
WHERE (dbo.AdvertiserAddressLink.AdvertiserId = 'AdvertisersID') <--see above
AND (dbo.Addresses.AddressType = 1 OR dbo.Addresses.AddressType = 0)
ORDER BY dbo.Addresses.AddressType DESC, dbo.Addresses.Sequence
It looks like you want to do TOP 1 in the second query based on a correlated parameter from the first?
You can use APPLY for this.
A simple example.
SELECT t.name, ca.name
FROM sys.tables t
CROSS APPLY (SELECT TOP 1 *
FROM sys.columns c
WHERE c.object_id=t.object_id
ORDER BY name) ca