Query migliori abbinamenti possibili e loro ordine
Domanda
Sto cercando di scrivere una domanda in questo senso:
select *
from tbl
where
col1 = 1
and col2 = 2
and col3 = 3
order by
...
;
Voglio prima tutti i risultati in cui soddisfano tutte le condizioni 3 WHERE
(3/3), poi tutti i risultati in cui corrispondono a qualsiasi 2 condizioni (2/3), e infine i risultati in cui qualsiasi 1 condizione viene soddisfatta (1/3) .
Ognuno di questi 3 set di risultati deve essere ordinato da (col4, col5, col6)
.
Posso farlo in una singola query?
Ad esempio:
campione http://img708.imageshack.us/img708/1646/sampletableresult1.jpg
Script per creare dati di test:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') AND type in (N'U'))
DROP TABLE [dbo].[MyTable]
GO
CREATE TABLE dbo.MyTable
(
col1 INT
, col2 INT
, col3 INT
, col4 INT
, col5 INT
, col6 INT
)
GO
INSERT dbo.MyTable (col1, col2, col3, col4, col5, col6)
SELECT 1,2,3,2,1,1 UNION ALL
SELECT 1,2,30,1,1,1 UNION ALL SELECT 1,20,30,1,1,1 UNION ALL
SELECT 10,20,3,1,1,1 UNION ALL SELECT 10,2,30,1,1,1 UNION ALL
SELECT 10,2,3,1,1,1 UNION ALL SELECT 10,20,30,1,1,1 UNION ALL
SELECT 1,2,3,1,1,1 UNION ALL SELECT 1,2,3,1,2,2 UNION ALL
SELECT 1,2,3,1,2,3 UNION ALL SELECT 1,20,3,1,1,1
GO
Soluzione
SELECT col1,
col2,
col3,
col4,
col5,
col6
FROM TableX
WHERE col1 = 1
OR col2 = 2
OR col3 = 3
ORDER BY (CASE WHEN col1 = 1 THEN 1 ELSE 0 END) +
(CASE WHEN col2 = 2 THEN 1 ELSE 0 END) +
(CASE WHEN col3 = 3 THEN 1 ELSE 0 END) DESC,
col4, col5, col6
o, per MS-Access:
ORDER BY IIF(col1 = 1,1,0) +
IIF(col2 = 2,1,0) +
IIF(col3 = 3,1,0) DESC,
col4, col5, col6
Altri suggerimenti
Sarebbe questo ottenere quello che vuoi? Technicly la vista in linea è neanche necessario, come si potrebbe ripetere l'istruzione case nell'ordine da.
select y.col1,
y.col2,
y.col3,
y.col4,
y.col5,
y.col6
from (
select col1,
col2,
col3,
case when col1 =1 and col2 = 2 and col3 = 3 then
1
when col1 = 1 and col2 = 2 and col3 <> 3 then
2
when col1 = 1 then
3
else
4
end x,
col4,
col5,
col6
from table
)y
order by y.x, col4, col5, col6
SELECT col1,
col2,
col3,
col4,
col5,
col6
FROM TableName
WHERE col1 = 1
OR col2 = 2
OR col3 = 3
ORDER BY (CASE WHEN col1 = 1 THEN 1 ELSE 0 END) DESC,
(CASE WHEN col2 = 2 THEN 1 ELSE 0 END) DESC,
(CASE WHEN col3 = 3 THEN 1 ELSE 0 END) DESC,
col4, col5, col6