Lemme try this again...Table definitions:
CVSource - Holds data on Dealers/Sources, one to many relationship on PK SourceID to CV referrals. It holds company name, contact name, contact info, etc. All text fields are nvarchar of various lengths.
CVReferrals has PK CVID, and holds individual customer information, such as name, address, DOB, etc. It also contains information related to the quote if it is sold and turned into a policy. That info would include Final Company (which company was finally selected), Final Premium (amount the customer actually paid for coverage), EffDate (policy effective date), and then, should policy later cancel, a cancel checkbox, cancellation date, cancel premium (how much was refunded), and a notes field.
CVInsQuotes, PK IQID, has many to one relationship with CVReferrals, linked on CVID. It has 4 columns, the PK, CVID, Company, and quote. Company is nvarchar(50), and quote is money.
CVOtherCompanies, PK ID, is only used as a row source with company names listed. for controls.
Now that I have table definitions...
SQL:
use tempdb;
go
/*
I have fields named for each of several companies. Imagine Progressive, National General, Geico, Safeco, Liberty Mutual. Each field is currency, and will contain the quote received from each of them.
*/
/* SETUP */
CREATE TABLE InsQuote(
QuoteDate DATE DEFAULT GETDATE(),
[Progressive] DECIMAL(6,2),
[National General] DECIMAL(6,2),
[Geico] DECIMAL(6,2),
[SafeCo] DECIMAL(6,2),
[Liberty Mutual] DECIMAL(6,2)
);
GO
INSERT INTO InsQuote VALUES ('1/1/2025',100.0,105.0,100.0,110.0,115.0),
('2/1/2025',105.0,100.0,110.0,112.0,110.0);
/* SOLUTION */
;WITH cteInsQuotes(QuoteDate, InsRate, Company)
AS (
SELECT iq.QuoteDate,FixedQuotes.Rate, FixedQuotes.Company
FROM InsQuote iq
CROSS APPLY (VALUES(Progressive,'Progressive'),
([National General],'National General'),
([Geico],'Geico'),
([SafeCo],'SafeCo'),
([Liberty Mutual],'Liberty Mutual'))
FixedQuotes(Rate, Company)
)
SELECT DISTINCT q.QuoteDate, topRates.Company, topRates.InsRate
FROM cteInsQuotes q
CROSS APPLY (
SELECT TOP (1) iq.Company, iq.InsRate
FROM cteInsQuotes iq
WHERE q.QuoteDate = iq.QuoteDate
ORDER BY iq.InsRate ASC
) topRates