我有一张这样的表
AMID Entry ------- --------- 1000 MARS 1001 JUPITER 1002 SATURN 1003 VENUS 1003 SATURN 1004 NEPTUNE 1004 SATURN 1005 JUPITER 1005 MARS
现在我想用特定的ENTRY值提取DISTINCT AMID值。 结束表应该是这样的
AMID Entry -------- -------- 1000 MARS 1001 JUPITER 1002 SATURN 1003 VENUS 1004 SATURN 1005 MARS
选择ENTRY值的条件是,
必须根据此优先级获取值:
- VENUS
- MARS
- JUPITER
- SATURN
- NEPTUNE
醇>
因此,如果任何AMID同时具有VENUS和MARS,则应该使用VENUS
MARS和SATURN,它应该采取MARS
NEPTUNE和JUPITER,它应该采用JUPITER。(按优先级选择)。
答案 0 :(得分:3)
您可以使用排名功能(如果您使用的是SQL Server 2008):
DECLARE @t TABLE (AMID INT, Entry VARCHAR(100))
INSERT @t
VALUES
( 1000 ,'MARS'),
( 1001 ,'JUPITER'),
( 1002 ,'SATURN'),
( 1003 ,'VENUS'),
( 1003 ,'SATURN'),
( 1004 ,'NEPTUNE'),
( 1004 ,'SATURN'),
( 1005 ,'JUPITER'),
( 1005 ,'MARS')
;WITH a AS(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY AMID ORDER BY
CASE Entry
WHEN 'VENUS' THEN 0
WHEN 'MARS' THEN 1
WHEN 'JUPITER' THEN 2
WHEN 'SATURN' THEN 3
WHEN 'NEPTUNE' THEN 4
END) num
FROM @t
)
SELECT AMID, Entry
FROM a
WHERE num = 1
答案 1 :(得分:3)
试试这个:
;WITH CTE AS (
SELECT *,ROW_NUMBER() OVER(PARTITION BY AMID ORDER BY T.PRIORITY) AS ROWNUM
FROM PLANETS P
JOIN
(
SELECT 1 PRIORITY, 'VENUS' AS NAME UNION ALL
SELECT 2, 'MARS' UNION ALL
SELECT 3, 'JUPITER' UNION ALL
SELECT 4, 'SATURN' UNION ALL
SELECT 5, 'NEPTUNE')T
ON T.NAME=P.[ENTRY]
)SELECT AMID,[ENTRY] FROM CTE WHERE ROWNUM=1
答案 2 :(得分:1)
尝试这个MySQL查询:
SELECT AMID, (CASE MIN(Entry) WHEN 1 THEN "VENUS"
WHEN 2 THEN "MARS"
WHEN 3 THEN "JUPITER"
WHEN 4 THEN "SATURN"
WHEN 5 THEN "NEPTUNE"
END) AS Entry
FROM (
SELECT AMID, (CASE Entry WHEN "VENUS" THEN 1
WHEN "MARS" THEN 2
WHEN "JUPITER" THEN 3
WHEN "SATURN" THEN 4
WHEN "NEPTUNE" THEN 5
END) AS Entry
FROM table_name
) a
GROUP BY AMID;
答案 3 :(得分:1)
为什么不直接将条目值放在自己的表中:
CREATE TABLE entry_value
(
entry VARCHAR(10) NOT NULL PRIMARY KEY,
value INT NOT NULL
);
INSERT INTO entry_value VALUES
('VENUS', 0),
('MARS', 1),
('JUPITER', 2),
('SATURN', 3),
('NEPTUNE', 4)
;
然后找到你想要的东西是微不足道的:
SELECT
a.amid,
(SELECT entry FROM entry_value where value = MIN(e.value)) AS entry
FROM amid a
JOIN entry_value e
ON e.entry = a.entry
GROUP BY a.amid
ORDER BY a.amid;
作为一个额外的好处,你可以在输入栏中添加一个外键,这样人们就不会把1000, 'PLUTO'
之类的垃圾放在那里。