I have this table in my SQL Server database:
CREATE TABLE HISTORICO
(
CODIGO VARCHAR(255),
FECHA VARCHAR(255),
VALOR VARCHAR(255),
);
The PK is composed of CODIGO
and FECHA
.
What I am looking for is to obtain all the records filtered by CODE and also for the DATE to exist in all the records of the same code. I attach a graphic example:
I want all records where the code is "AAA" but also exist (by DATE) in "BBB" and in "CCC".
That is, where the date is also the same for all CODIGO
.
I write the query that I currently use and it works correctly.
I think it can be done better, although right now I can't find a way. Does somey know how to improve the query obtaining the same result?
3条答案
按热度按时间yhuiod9q1#
I believe this is what you're after: SQL Fiddle Example
Explanation
The innermost query figures out how many distinct values for CODIGO exist in the table. Since you only want records where every existing value of CODIGO has a matching value of FECHA we need to know how many CODIGO values there are in total.
The next layer up returns all values of FECHA for which every value of CODIGO exists; it does this by grouping all FECHA records then counting the number of different (distinct) values of CODIGO are in that set, and comparing that to the number we calculated earlier.
The outermost query returns all records which have this FECHA value; since those are the ones we care about.
Note: there may be more efficient solutions to this out there; I've just knocked up a first pass at what should meet your functional requirement. If you have an index of FECHA (idealy your primary key & clustered index contains FECHA followed by CODIGO) this should perform pretty well.
Your Requirements
Just in case there's any confusion, here's how I understood your requirement - please say if this is incorrect, as if it is this solution won't be appropriate:
You want to:
Note: "every possible value of CODIGO" is based on the values that exist across the HISTORICO table itself; i.e. if we were to delete the records where CODIGO='CCC' then all records would be returned, since both AAA and BBB have values with FECHA 2022 and 2023, and there would be no other values of CODIGO (based on the sample data in your screenshots.
23c0lvtd2#
Just a guess, but it seems you can use the
WITH TIES
option in concert with the window functionrow_number()
acruukt93#
I would guess you want to look for sets that include all
FECHA
values.You can do:
Change
3
by the number ofFECHA
you want to check.