SQL Server, How to create two select statement in one table - sql-server

I make two select statements with different result sets,
Please help me to make those two select statements show the their result in one table,
DECLARE #EmpID INT
SELECT #EmpID = SubCategoryId
FROM dbo.Product
WHERE ProductId = 13
SELECT Product.ProductId
, Product.ProductName
, Product.ProductPrice
, Product.ProductQuantity
, Product.SubCategoryId AS ForUpdate
, SubCategory.SubCategoryName
, SubCategory.SubCategoryId
FROM Product
INNER JOIN ProductUnderCategory
ON ProductUnderCategory.ProductId = Product.ProductId
INNER JOIN SubCategory
ON ProductUnderCategory.SubCategoryId = SubCategory.SubCategoryId
WHERE Product.ProductId = 13
SELECT Property.Propertyid
, Property.PropertyName
, ProductProperties.PropertyValue
FROM Property
LEFT JOIN ProductProperties
ON Property.PropertyId = ProductProperties.PropertyId AND ProductProperties.ProductId = 13
WHERE Property.Propertyid IN (
SELECT PropertyId
FROM CategoryProperty
WHERE CategoryProperty.SubCategoryId = CategoryProperty.SubCategoryId AND CategoryProperty.SubCategoryId = #EmpID
)

I'm assuming you want the properties for each product (not a union, but a join). Something like this:
DECLARE #EmpID INT
SELECT #EmpID = SubCategoryId
FROM dbo.Product
WHERE ProductId = 13
SELECT Product.ProductId
, Product.ProductName
, Product.ProductPrice
, Product.ProductQuantity
, Product.SubCategoryId AS ForUpdate
, SubCategory.SubCategoryName
, SubCategory.SubCategoryId
, Property.Propertyid
, Property.PropertyName
, ProductProperties.PropertyValue
FROM Product
INNER JOIN ProductUnderCategory
ON ProductUnderCategory.ProductId = Product.ProductId
INNER JOIN SubCategory
ON ProductUnderCategory.SubCategoryId = SubCategory.SubCategoryId
LEFT JOIN ProductProperties
on ProductProperties.ProductID = Product.ProductID
left join Property
ON Property.PropertyId = ProductProperties.PropertyId
and Property.Propertyid IN (
SELECT PropertyId
FROM CategoryProperty
WHERE
CategoryProperty.SubCategoryId = CategoryProperty.SubCategoryId
AND CategoryProperty.SubCategoryId = #EmpID
)
WHERE Product.ProductId = 13

You probably can do something like the following - if a column doesn't exist in the 1st select you need to include whatever value is appropriate and must name the column. if a column doesn't exist in the subsequent selects then simply return null/''/0 or whatever you need as a value;
select Product.ProductId, Product.ProductName, Product.ProductPrice, Product.ProductQuantity, '' as someColumn, ....
from ....
union [all]
Select Property.Propertyid, Property.PropertyName, ProductProperties.PropertyValue, NULL (for ProductQuantity), ProductProperties.someColumn
from .....

Related

How to update and insert with list of values in sql

I get a list of values from the select query. From the list, I am checking whether the items in the list is available in the table. If the values exist, I need to update the values else Insert the list into the Table.
With the list, I can insert the list of values in the table.
How to check and update the list in sql.
My Query :
WITH pq AS
(
SELECT A.[ProductId] ,A.[Quantity],A.[OrderId],D.[ProductName],E.[SpecialPrice],E.[SpecialPrice]*A.[Quantity] AS SPrice FROM [Table1] A
LEFT JOIN [Table2] B ON A.[OrderId] = B.[OrderId] INNER JOIN [Table3] D
ON A.[ProductId] = D.[ProductId] INNER JOIN [Table4] E
ON A.[ProductId] = E.[ProductId] WHERE B.[CustomerId] = 1
AND A.[OrderId] = 77
)
IF (EXISTS(SELECT [ProductId] FROM [Table5] WHERE [ProductId] = A.[ProductId]))
BEGIN
UPDATE [Table5]
SET [Quantity] = A.[Quantity]
WHERE B.[CustomerId] = 1 AND [ProductId] = A.[ProductId]
END
ELSE
BEGIN
INSERT INTO [Table5]
([ProductId],[ProductName],[Quantity],[Price],[TotalAmount])
SELECT
[ProductId],[ProductName],[Quantity],[SpecialPrice],SPrice
FROM pq;
END
Any suggestions will be greatly helpful.
EDIT : SELECT QUERY RESULT
ProductId Quantity
65 2
64 1
Assuming you're on SQL Server 2008 or above, the MERGE statement will solve your problem:
MERGE Table5 TRG
USING (
SELECT
A.ProductId,
A.Quantity,
A.OrderId,
D.ProductName,
E.SpecialPrice,
(E.SpecialPrice * A.Quantity) SPrice
FROM Table1 A
LEFT JOIN Table2 B ON A.OrderId = B.OrderId
INNER JOIN Table3 D ON A.ProductId = D.ProductId
INNER JOIN Table4 E ON A.ProductId = E.ProductId
WHERE
B.CustomerId = 1
AND A.OrderId = 77
) SRC
ON TRG.ProductID = SRC.ProductID
WHEN MATCHED THEN
UPDATE SET TRG.Quantity = SRC.Quantity
WHEN NOT MATCHED BY TARGET THEN
INSERT (
ProductId
, ProductName
, Quantity
, Price
, TotalAmount
)
VALUES (
SRC.ProductId
, SRC.ProductName
, SRC.Quantity
, SRC.SpecialPrice
, SRC.SPrice)
;
You can move the SELECT query out to a CTE for legibility like you did in your example.

Return Results Even If CTE Doesn't Resolve

I have a stored procedure on my SQL Server that consolidates a range of fields for use in SSRS for Report Builder. The procedure is fed a FileId and then works its logic. It works as intended until the File can't find or reference the Solicitor and Arresting Officer fields.
I need this to return a result even if the fileId does not have an Arresting Officer or Solicitor associated. I'm sure its something simple. Basically if the CTE returns nothing from the query, I still need a default row.
ALTER PROCEDURE [dbo].[GetRollCallData]
#Ids VARCHAR(255),
#LexiconId INT,
#UUID UNIQUEIDENTIFIER,
#ReadOnly INT
AS
DECLARE #TableCode INT
SET #TableCode = 58
IF #Ids <> ''
BEGIN
EXEC InsertInSelectionCache #Ids, #UUID, #TableCode, 0
IF #ReadOnly = 1
WITH DOACTE AS(
SELECT ROW_NUMBER() OVER(PARTITION BY [File].Id ORDER BY CustomRecordsetId DESC) AS RowNumber, [File].*, FileType2Lexicon.Label as FileTypeLabel, [People].DefaultPhone, [People].InvertedName, CustomField.Name as FieldLabel, CustomFieldValue.Value as FieldValue
FROM FileType2Lexicon, SelectionCache, [People], [File]
INNER JOIN [CustomRecordSet]
ON [CustomRecordset].RecordId = [File].Id
INNER JOIN CustomFieldValue
ON [CustomRecordset].Id = CustomFieldValue.CustomRecordsetId
INNER JOIN [CustomField2Lexicon]
ON CustomField2Lexicon.CustomFieldId = CustomFieldValue.CustomFieldId
INNER JOIN [CustomField]
ON CustomField.Id = CustomField2Lexicon.CustomFieldId
WHERE [File].Id = SelectionCache.RecordId
AND SelectionCache.UUID = #UUID
AND SelectionCache.TableCode = #TableCode -- this is the code for File table
AND [File].Id <> 0
AND [File].FileTypeId = FileType2Lexicon.FileTypeId
AND FileType2Lexicon.LexiconId = #LexiconId
AND [File].ClientIdString = [People].ClientIdString
AND CustomFieldValue.Value <> ''),
SolicitorCTE AS(
SELECT [People].Name AS SolicitorName, [File].Id
FROM SelectionCache, [File]
INNER JOIN [People2File]
ON [People2File].FileId = [File].Id
INNER JOIN [Role2Lexicon]
ON [Role2Lexicon].RoleId = [People2File].RoleId
INNER JOIN [People]
ON [People].Id = [People2File].PeopleId
WHERE
[File].Id = SelectionCache.RecordId
AND SelectionCache.UUID = #UUID
AND SelectionCache.TableCode = #TableCode -- this is the code for File table
AND [File].Id <> 0
AND [Role2Lexicon].Label = 'Solicitor'),
ArrestingOfficerCTE AS(
SELECT ROW_NUMBER() OVER(PARTITION BY [File].Id ORDER BY [People].InvertedName ASC) AS RowNumber, [People].Name AS ArrestingOfficerName, [People].CompanyName AS ArrestingOfficerCompany, [File].Id
FROM SelectionCache, [File]
INNER JOIN [People2File]
ON [People2File].FileId = [File].Id
INNER JOIN [Role2Lexicon]
ON [Role2Lexicon].RoleId = [People2File].RoleId
INNER JOIN [People]
ON [People].Id = [People2File].PeopleId
WHERE
[File].Id = SelectionCache.RecordId
AND SelectionCache.UUID = #UUID
AND SelectionCache.TableCode = #TableCode -- this is the code for File table
AND [File].Id <> 0
AND [Role2Lexicon].Label = 'Arresting Officer'),
PivotCTE AS(
SELECT *
FROM
(Select Id, FieldLabel, FieldValue FROM DOACTE) AS Source
PIVOT(
MAX(FieldValue) FOR FieldLabel IN ([Date_Arrest], [Graphic_Client], [Ticket_1], [Ticket_2], [Ticket_3], [Ticket_4], [Ticket_5], [Charge_1], [Charge_2], [Charge_3], [Charge_4], [Charge_5])) as Pvt
)
SELECT DOACTE.*, COALESCE(ArrestingOfficerCTE.ArrestingOfficerCompany, 'NULL')AS ArrestingOfficerCompany, COALESCE(ArrestingOfficerCTE.ArrestingOfficerName, 'NULL') AS ArrestingOfficerName, SolicitorCTE.SolicitorName, PivotCTE.[Date_Arrest], dbo.GetImagebyId(PivotCTE.[Graphic_Client]) as Photo, PivotCTE.[Ticket_1], PivotCTE.[Ticket_2], PivotCTE.[Ticket_3], PivotCTE.[Ticket_4], PivotCTE.[Ticket_5], PivotCTE.[Charge_1], PivotCTE.[Charge_2], PivotCTE.[Charge_3], PivotCTE.[Charge_4], PivotCTE.[Charge_5]
FROM DOACTE
INNER JOIN
PivotCTE
ON DOACTE.Id = PivotCTE.Id
INNER JOIN
SolicitorCTE
ON DOACTE.Id = SolicitorCTE.Id
INNER JOIN
ArrestingOfficerCTE
ON DOACTE.Id = ArrestingOfficerCTE.Id
WHERE DOACTE.RowNumber = 1
AND ArrestingOfficerCTE.RowNumber = 1
ELSE
DELETE SelectionCache
WHERE UUID = #UUID
AND TableCode = #TableCode
END
You can left join for optional results. I also needed to add a null check for the Arresting officer to the where caluse so that this didn't exclude records despite the left join.
SELECT DOACTE.*, COALESCE(ArrestingOfficerCTE.ArrestingOfficerCompany, 'NULL')AS ArrestingOfficerCompany, COALESCE(ArrestingOfficerCTE.ArrestingOfficerName, 'NULL') AS ArrestingOfficerName, SolicitorCTE.SolicitorName, PivotCTE.[Date_Arrest], dbo.GetImagebyId(PivotCTE.[Graphic_Client]) as Photo, PivotCTE.[Ticket_1], PivotCTE.[Ticket_2], PivotCTE.[Ticket_3], PivotCTE.[Ticket_4], PivotCTE.[Ticket_5], PivotCTE.[Charge_1], PivotCTE.[Charge_2], PivotCTE.[Charge_3], PivotCTE.[Charge_4], PivotCTE.[Charge_5]
FROM DOACTE
INNER JOIN
PivotCTE
ON DOACTE.Id = PivotCTE.Id
LEFT JOIN
SolicitorCTE
ON DOACTE.Id = SolicitorCTE.Id
LEFT JOIN
ArrestingOfficerCTE
ON DOACTE.Id = ArrestingOfficerCTE.Id
WHERE DOACTE.RowNumber = 1
AND ( ArrestingOfficerCTE.RowNumber = 1 or ArrestingOfficerCTE.RowNumber is null )
Can you try:
SELECT DOACTE.*, COALESCE(ArrestingOfficerCTE.ArrestingOfficerCompany, 'NULL')AS ArrestingOfficerCompany, COALESCE(ArrestingOfficerCTE.ArrestingOfficerName, 'NULL') AS ArrestingOfficerName, SolicitorCTE.SolicitorName, PivotCTE.[Date_Arrest], dbo.GetImagebyId(PivotCTE.[Graphic_Client]) as Photo, PivotCTE.[Ticket_1], PivotCTE.[Ticket_2], PivotCTE.[Ticket_3], PivotCTE.[Ticket_4], PivotCTE.[Ticket_5], PivotCTE.[Charge_1], PivotCTE.[Charge_2], PivotCTE.[Charge_3], PivotCTE.[Charge_4], PivotCTE.[Charge_5]
into #Results
FROM DOACTE
INNER JOIN
PivotCTE
ON DOACTE.Id = PivotCTE.Id
INNER JOIN
SolicitorCTE
ON DOACTE.Id = SolicitorCTE.Id
INNER JOIN
ArrestingOfficerCTE
ON DOACTE.Id = ArrestingOfficerCTE.Id
WHERE DOACTE.RowNumber = 1
AND ArrestingOfficerCTE.RowNumber = 1
if ((select cout(*) from #Results) = 0)
begin
insert into #Results
select
.......your default values......
end
select * from #Results
drop table #Results
This is pretty much liebs19's answer, so I upvoted his since he got there first. I think the answer comes down to LEFT JOINing where you're INNER. Since I rewrote your query so I could actually understand what was going on and I made some changes you may or may not want, so I'll leave it here in case it's useful.
Mine is more lines than yours partially because I format differently, partially because I'm using a temp table to do once what you do around 4 times. Thing about CTE's is that when you stack them like this you're likely to get some really gnarly performance. The CTE's act basically like an on-the-fly view, and their SQL pretty much gets repeated everywhere. I'm taking your limiting [File] and moving it into a temp table. Then I'm pivoting it into another one (since this further limits things based on RowNumber being 1. Then I just use this with the 2 CTE's at the end and into your final result.
Lastly, SELECT * ... is evil. I only use it when I'm poking around querying for something. Putting it into a sproc like this will cause you issues as the schema or CTE's or so on change. When you're making a sproc, name every column, it'll bite you much less in the future.
Here it is, feel free to ignore if you don't find it useful:
ALTER PROCEDURE [dbo].[GetRollCallData]
#Ids VARCHAR(255),
#LexiconId INT,
#UUID UNIQUEIDENTIFIER,
#ReadOnly INT
AS
BEGIN
DECLARE #TableCode INT = 58;
IF #Ids <> ''
BEGIN
EXEC InsertInSelectionCache #Ids, #UUID, #TableCode, 0
IF #ReadOnly = 1
BEGIN
SELECT
-- Add any other fully qualified columns. * is evil for sprocs. Only good for poking around in your own queries.
AllFiles.Id
INTO #SelectionFile
FROM
[File] AllFiles
INNER JOIN SelectionCache Cache
ON Cache.RecordId = AllFiles.Id
AND Cache.UUID = #UUID
AND Cache.TableCode = #TableCode -- this is the code for File table
WHERE
AllFiles.Id <> 0
;WITH DOACTE AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY SelectionFile.Id ORDER BY CustomRecordsetId DESC) AS RowNumber
, SelectionFile.Id AS FileId
-- [Replace with any other columns that you selected from [File] at the top.]
, Lexicon.Label AS FileTypeLabel
, [People].DefaultPhone
, [People].InvertedName
, CustomField.Name AS FieldLabel
, CustomFieldValue.Value AS FieldValue
FROM
#SelectionFile SelectionFile
INNER JOIN FileType2Lexicon Lexicon
ON Lexicon.FileTypeId = SelectionFile.FileTypeId
AND Lexicon.LexiconId = #LexiconId
INNER JOIN [People]
ON [People].ClientIdString = SelectionFile.ClientIdString
INNER JOIN [CustomRecordSet]
ON [CustomRecordset].RecordId = SelectionFile.Id
INNER JOIN CustomFieldValue
ON [CustomRecordset].Id = CustomFieldValue.CustomRecordsetId
AND CustomFieldValue.Value <> ''
INNER JOIN [CustomField2Lexicon]
ON CustomField2Lexicon.CustomFieldId = CustomFieldValue.CustomFieldId
INNER JOIN [CustomField]
ON CustomField.Id = CustomField2Lexicon.CustomFieldId
)
SELECT
Pvt.FileId
-- [Replace with any other columns that you selected from DOACTE you want to propagate to the end.]
, Pvt.[Date_Arrest]
, Pvt.[Graphic_Client]
, Pvt.[Ticket_1]
, Pvt.[Ticket_2]
, Pvt.[Ticket_3]
, Pvt.[Ticket_4]
, Pvt.[Ticket_5]
, Pvt.[Charge_1]
, Pvt.[Charge_2]
, Pvt.[Charge_3]
, Pvt.[Charge_4]
, Pvt.[Charge_5]
INTO #PivotedFile
FROM
(
SELECT
FileId
-- [Replace with any other columns that you selected from DOACTE you want to propagate to the end.]
, FieldLabel
, FieldValue
, FieldLabel AS PivotFieldLabel
, FieldValue AS PivotFieldValue
FROM
DOACTE
WHERE
RowNumber = 1
) AS Source
PIVOT
(
MAX(PivotFieldValue)
FOR PivotFieldLabel
IN
(
[Date_Arrest]
, [Graphic_Client]
, [Ticket_1]
, [Ticket_2]
, [Ticket_3]
, [Ticket_4]
, [Ticket_5]
, [Charge_1]
, [Charge_2]
, [Charge_3]
, [Charge_4]
, [Charge_5]
)
) as Pvt
;WITH SolicitorCTE AS
(
SELECT
[People].Name AS SolicitorName
, SelectedFiles.FileId
FROM
#PivotedFile SelectedFiles
INNER JOIN [People2File]
ON [People2File].FileId = SelectedFiles.FileId
INNER JOIN [Role2Lexicon]
ON [Role2Lexicon].RoleId = [People2File].RoleId
AND [Role2Lexicon].Label = 'Solicitor'
INNER JOIN [People]
ON [People].Id = [People2File].PeopleId
)
, ArrestingOfficerCTE AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY SelectionFile.Id ORDER BY [People].InvertedName ASC) AS RowNumber
, [People].Name AS ArrestingOfficerName
, [People].CompanyName AS ArrestingOfficerCompany
, SelectedFiles.FileId
FROM
#PivotedFile SelectedFiles
INNER JOIN [People2File]
ON [People2File].FileId = SelectedFiles.FileId
INNER JOIN [Role2Lexicon]
ON [Role2Lexicon].RoleId = [People2File].RoleId
AND [Role2Lexicon].Label = 'Arresting Officer'
INNER JOIN [People]
ON [People].Id = [People2File].PeopleId
)
SELECT
SelectedFiles.Id
-- [Replace with any other columns that you selected from DOACTE you want to propagate to the end.]
, COALESCE(ArrestingOfficerCTE.ArrestingOfficerCompany, 'NULL') AS ArrestingOfficerCompany
, COALESCE(ArrestingOfficerCTE.ArrestingOfficerName, 'NULL') AS ArrestingOfficerName
, SolicitorCTE.SolicitorName
, SelectedFiles.[Date_Arrest]
, dbo.GetImagebyId(SelectedFiles.[Graphic_Client]) as Photo
, SelectedFiles.[Ticket_1]
, SelectedFiles.[Ticket_2]
, SelectedFiles.[Ticket_3]
, SelectedFiles.[Ticket_4]
, SelectedFiles.[Ticket_5]
, SelectedFiles.[Charge_1]
, SelectedFiles.[Charge_2]
, SelectedFiles.[Charge_3]
, SelectedFiles.[Charge_4]
, SelectedFiles.[Charge_5]
FROM #PivotedFile SelectedFiles
LEFT JOIN SolicitorCTE
ON SelectedFiles.FileId = SolicitorCTE.FileId
LEFT JOIN ArrestingOfficerCTE
ON SelectedFiles.FileId = ArrestingOfficerCTE.FileId
AND ArrestingOfficerCTE.RowNumber = 1
DROP TABLE #SelectionFile
DROP TABLE #PivotedFile
END
ELSE
DELETE SelectionCache
WHERE
UUID = #UUID
AND TableCode = #TableCode
END
END
(If you do use it, read the -- [Replace...] comments.

UNION select sql statement returns duplicate results

My objective is to have one record with both HomeNumber & OfficeNumber and I'm keeping the PersonID to reference the customer table. I'm thinking I shouldn't even be using a UNION but maybe a select query from two nested sub queries.
The results returned look like this.
1A370535-9432-45B9-8F08-004F040EE196 '' ''
1A370535-9432-45B9-8F08-004F040EE196 6127319561 ''
E8FA1667-416C-4639-ADDC-02143D651B4E '' 6512096719
E8FA1667-416C-4639-ADDC-02143D651B4E 6515786963 ''
Here my query:
SELECT PhoneNumbers.PersonID, PhoneNumbers.HomeNum, PhoneNumbers.OfficeNum
FROM (
SELECT PhoneHub.PersonID, ISNULL(PhoneHub.PhoneNbr, '') AS HomeNum, '' AS OfficeNum
FROM
--PhoneType INNER JOIN
PhoneHub --ON PhoneType.ID = PhoneHub.TypeID
WHERE
(PhoneHub.FranID = #FranID) AND
(PhoneHub.TypeID = '28321161-668e-4a56-90be-67a146fa1353') -- Home# ID
UNION
SELECT PhoneHub.PersonID, '' AS HomeNum, ISNULL(PhoneHub.PhoneNbr, '') AS OffNum
FROM
--PhoneType AS PhoneType_2 INNER JOIN
PhoneHub --AS PhoneHub ON PhoneType_2.ID = PhoneHub.TypeID
WHERE
(PhoneHub.FranID = #FranID) AND
(PhoneHub.TypeID = '02a4125b-b968-4dc6-9734-7f75f45f7635') --Office# ID
) AS PhoneNumbers
ORDER BY PhoneNumbers.PersonID
Table Schema - PhoneHub
PK ID uniqueidentifier
FK FranID uniqueidentifier Franchise.ID
FK PersonID uniqueidentifier Customer.ID
FK TypeID uniqueidentifier PhoneType.ID
PhoneNbr nvarchar(20)
PhoneExt nvarchar(10)
IsDefault bit
This looks like a pivot requirement.
SELECT PersonID,
Max(case when TypeID = '28321161-668e-4a56-90be-67a146fa1353'
then PhoneNbr End) HomeNum,
Max(case when TypeID = '02a4125b-b968-4dc6-9734-7f75f45f7635'
then PhoneNbr End) OfficeNum
FROM
PhoneHub
WHERE
PhoneHub.FranID = #FranID
GROUP BY PersonID
Select a.PersonID,Coalesce(home.PhoneNbr, '') AS HomeNum,Coalesce(office.PhoneNbr, '') AS OffNum from
(
SELECT PhoneHub.PersonID
FROM
PhoneHub
WHERE
(PhoneHub.FranID = #FranID) AND
(PhoneHub.TypeID = '28321161-668e-4a56-90be-67a146fa1353')
UNION
SELECT PhoneHub.PersonID
FROM
PhoneHub
WHERE
(PhoneHub.FranID = #FranID) AND
(PhoneHub.TypeID = '02a4125b-b968-4dc6-9734-7f75f45f7635')
) as a
left join PhoneHub home on (home.PersonID = a.PersonID) and (home.FranID = #FranID) AND (home.TypeID = '28321161-668e-4a56-90be-67a146fa1353')
left join PhoneHub office on (office.PersonID = a.PersonID) and (office.FranID = #FranID) AND (office.TypeID = '02a4125b-b968-4dc6-9734-7f75f45f7635')
order by a.PersonID

Multiple COUNT(*) with join

I have to COUNT some rows from multiple tables. Before I can do multiple COUNT I will have to subselect. The problem here is that I need to JOIN some values in order to get the right result.
SELECT
sponsor.Name As SponsorName,
COUNT(participants.[Table]) AS ParticipantCount,
( SELECT
COUNT(guestcards.[Table])
FROM
guestcards
WHERE
guestcards.EventID = #EventID
AND
guestcards.[Table] = #Table
AND
guestcards.SponsorID = participants.SponsorID
-- Here lies the problem.
-- I will need to check up on another value to ensure I get the right rows, but participants.SponsorID is not here because of no join :-(
) AS GuestParticipantCount
FROM
participants
LEFT JOIN
sponsor
ON
sponsor.ID = participants.SponsorID
WHERE
participants.EventID = #EventID
AND
participants.[Table] = #Table
GROUP BY
sponsor.Name
Guestcards table holds: sponsorid, eventid, tablename
Participantstable holds: sponsorid, eventid, tablename
Sponsor table holds: id, name
I need to count how many "Participants" there are and how many "Guestcards" that in a particulary event. These participants have a table (where they should sit) and so does the guestcards. I need to check up on if its the same "table" where they sit.
So I need to count how many are sitting at table "A1" or table "A2" etc.
The result I am after is like:
"Sponsor Name has 5 participants and 3 guestcards. They sit on A1"
I hope I made my self clear
Here's exact equivalent of you query (grouping on sponsor.Name):
SELECT sponsor.name,
COALESCE(SUM(participantCount), 0),
COALESCE(SUM(guestcardsCount), 0)
FROM (
SELECT sponsorId, COUNT(*) AS participantCount
FROM participants
WHERE eventId = #eventId
AND [table] = #table
GROUP BY
sponsorId
) p
FULL JOIN
(
SELECT sponsorId, COUNT(*) AS guestcardsCount
FROM guestdcards
WHERE eventId = #eventId
AND [table] = #table
GROUP BY
sponsorId
) g
ON g.sponsorId = p.sponsorId
FULL JOIN
sponsor s
ON s.id = COALESCE(p.sponsorId, g.sponsorId)
GROUP BY
s.sponsorName
However, I believe you want something more simple:
SELECT sponsorName, participantCount, guestcardsCount
FROM sponsor s
CROSS APLLY
(
SELECT COUNT(*) AS participantCount
FROM participants
WHERE sponsorId = s.id
AND eventId = #eventId
AND [table] = #table
) p
CROSS APLLY
(
SELECT COUNT(*) AS guestcardsCount
FROM guestdcards
WHERE sponsorId = s.id
AND eventId = #eventId
AND [table] = #table
) g
Update:
SELECT sponsor.name,
COALESCE(participantCount, 0),
COALESCE(guestcardsCount, 0)
FROM (
SELECT sponsorId, COUNT(*) AS participantCount
FROM participants
WHERE eventId = #eventId
AND [table] = #table
GROUP BY
sponsorId
) p
FULL JOIN
(
SELECT sponsorId, COUNT(*) AS guestcardsCount
FROM guestdcards
WHERE eventId = #eventId
AND [table] = #table
GROUP BY
sponsorId
) g
ON g.sponsorId = p.sponsorId
JOIN sponsor s
ON s.id = COALESCE(p.sponsorId, g.sponsorId)

Get the most value from another column

I want to get data historical and the production. My stored procedure is as follows:
ALTER PROCEDURE [dbo].[pCaRptACInactivas](
#CodAsesor VARCHAR(15),
#CodOficina VARCHAR(4))
AS
SET NOCOUNT ON
DECLARE #CodArbolConta VARCHAR(25)
IF #CodOficina = '%'
SET #CodArbolConta = '%'
ELSE
SELECT #CodArbolConta = CodArbolConta + '%' FROM tClOficinas WHERE CodOficina LIKE #CodOficina
SELECT
tabACInactivas.CodOficina,
tabACInactivas.NomOficina,
tabACInactivas.NomAsesor,
MAX(tabACInactivas.CodPrestamo) CodPrestamo,
tabACInactivas.CodAsociacion,
tabACInactivas.NombreAsociacion,
MAX(tabACInactivas.Ciclo) AS Ciclo,
COUNT(DISTINCT tabACInactivas.CodUsuario) AS CantSocias,
MAX(tabACInactivas.FechaEstado) AS FechaCancelacion--,
FROM ( SELECT tClOficinas.CodOficina, tClOficinas.NomOficina, tCaClAsesores.CodAsesor, tCaClAsesores.NomAsesor, tCaPrestamos.CodPrestamo, tCaAsociacion.CodAsociacion, tCaAsociacion.NombreAsociacion, tCaPrestamos.Ciclo, tCaPrCliente.CodUsuario, tCaPrestamos.FechaEstado, tClParametros.FechaProceso FROM tCaPrestamos WITH(NOLOCK) INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaPrestamos.CodProducto INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaPrestamos.CodOficina INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaPrestamos.CodAsociacion INNER JOIN tCaPrCliente WITH(NOLOCK) ON tCaPrCliente.CodPrestamo = tCaPrestamos.CodPrestamo INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor WHERE tCaPrestamos.Estado = 'CANCELADO' AND DATEDIFF(DAY, tCaPrestamos.FechaEstado, tClParametros.FechaProceso) > 30 AND NOT EXISTS(SELECT 1
FROM tCaPrestamos Pr
INNER JOIN tCaPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
AND Pr.FechaDesembolso >= tCaPrestamos.FechaEstado
AND Pr.CodAsociacion = tCaPrestamos.CodAsociacion
) AND tCaProducto.Tecnologia = 3 AND tCaPrestamos.CodAsesor LIKE #CodAsesor AND tCaPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE #CodArbolConta)
UNION ALL
SELECT tClOficinas.CodOficina, tClOficinas.NomOficina, tCaClAsesores.CodAsesor, tCaClAsesores.NomAsesor, tCaHPrestamos.CodPrestamo, tCaAsociacion.CodAsociacion, tCaAsociacion.NombreAsociacion, tCaHPrestamos.Ciclo, tCaHPrCliente.CodUsuario, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso FROM tCaHPrestamos WITH(NOLOCK) INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaHPrestamos.CodProducto INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaHPrestamos.CodOficina INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaHPrestamos.CodAsociacion INNER JOIN tCaHPrCliente WITH(NOLOCK) ON tCaHPrCliente.CodPrestamo = tCaHPrestamos.CodPrestamo INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor WHERE tCaHPrestamos.Estado = 'CANCELADO' AND DATEDIFF(DAY, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso) > 30 AND NOT EXISTS(SELECT 1
FROM tCaHPrestamos Pr
INNER JOIN tCaHPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
AND Pr.FechaDesembolso >= tCaHPrestamos.FechaEstado
AND Pr.CodAsociacion = tCaHPrestamos.CodAsociacion
) AND tCaProducto.Tecnologia = 3 AND tCaHPrestamos.CodAsesor LIKE #CodAsesor AND tCaHPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE #CodArbolConta)
)tabACInactivas
GROUP BY tabACInactivas.CodAsociacion, tabACInactivas.NombreAsociacion, tabACInactivas.NomOficina, tabACInactivas.CodOficina, tabACInactivas.NomAsesor
I want the CantSocias column takes the most value of the Ciclo column, but not working
That stored procedure that you have posted up is way too large and blocky to even try to interpret and understand. So I will go off of your last sentence:
I want the CantSocias column takes the most value of the Ciclo column,
but not working
Basically if you want to set a specific column to that, you can do something like this:
update YourTable
set CantSocias =
(
select max(Ciclo)
from YourOtherTable
)
-- here is where you can put a conditional WHERE clause
You may need to create a sub query to get the most value of Ciclo and join back to your query.
An example of what I mean is here:
create table #Product
(
ID int,
ProductName varchar(20)
)
insert into #Product(ID, ProductName)
select 1,'ProductOne'
union
select 2,'ProductTwo'
create table #ProductSale
(
ProductID int,
Number int,
SalesRegion varchar(20)
)
insert into #ProductSale(ProductID,Number,SalesRegion)
select 1,1500,'North'
union
select 1, 1200, 'South'
union
select 2,2500,'North'
union
select 2, 3200, 'South'
--select product sales region with the most sales
select * from #Product p
select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID
--combining
select
p.ID,
p.ProductName,
tp.Bestsale,
ps.SalesRegion
from
#Product p
inner join
(select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID) as tp on p.ID = tp.ProductID
inner join
#ProductSale ps on p.ID = ps.ProductID and tp.Bestsale = ps.Number

Resources