如何解决列名称为
我在SQL Server中有下表:
CREATE TABLE table123
(
ID INT PRIMARY KEY,Price1 INT,Price2 INT,Price3 INT,another_field int
)
INSERT INTO table123
VALUES (1,4,3,2,112)
INSERT INTO table123
VALUES (2,1,113)
INSERT INTO table123
VALUES (3,5,6,114)
INSERT INTO table123
VALUES (4,115)
GO
ID Price1 Price2 Price3 another_field
1 4 3 2 112
2 2 3 1 113
3 5 4 6 114
4 3 4 6 115
我想要的是三个价格的最大值,但是我想知道哪一列确实值。像这张桌子一样:
ID Price PriceLabel another_field
1 4 Price1 112
2 3 Price2 113
3 6 Price3 114
4 6 Price3 115
我已经看到多种解决方案来获取价格的最大值,并采用它们:
WITH temp1 as (
SELECT ID,( CASE rn
WHEN 1 THEN Price1
WHEN 2 THEN Price2
ELSE Price3
END ) AS Price,( CASE rn
WHEN 1 THEN 'Price1'
WHEN 2 THEN 'Price2'
ELSE 'Price3'
END ) AS "PriceLabel",another_field
FROM table123 a
CROSS JOIN (SELECT 1 AS rn
UNION
SELECT 2
UNION
SELECT 3) b
),temp2 as (select ID,max(Price) AS Price from temp1 group by ID)
select t2.*,t1.PriceLabel,t1.another_field
from temp2 t2
join temp1 t1 on t1.ID = t2.ID AND t1.Price = t2.Price
GO
我觉得有比这更聪明的解决方案。任何帮助表示赞赏。
解决方法
好吧,您可以手动检测哪个价格具有最大值(假设价格不能为负):
SELECT
ID,CASE
WHEN Price1 IS NOT NULL AND Price1 >= ISNULL(Price2,0) AND Price1 >= ISNULL(Price3,0) THEN Price1
WHEN Price2 IS NOT NULL AND Price2 >= ISNULL(Price3,0) THEN Price2
ELSE Price3
END as Price,0) THEN 'Price1'
WHEN Price2 IS NOT NULL AND Price2 >= ISNULL(Price3,0) THEN 'Price2'
ELSE 'Price3'
END as PriceLabel,another_field
FROM table123
但是最好将价格移到单独的表格(ID,索引,价格)
,尽管已接受answr,但解决此问题的另一种方法是使用unpivot和rank来获取值。如果由于某种原因,您有三列以上,那么您将只需要修改unpivot语句来容纳它即可。
declare @table123 table
(
ID INT PRIMARY KEY,Price1 INT,Price2 INT,Price3 INT,another_field int
)
INSERT INTO @table123
VALUES (1,4,3,2,112)
INSERT INTO @table123
VALUES (2,1,113)
INSERT INTO @table123
VALUES (3,5,6,114)
INSERT INTO @table123
VALUES (4,115)
select * from @table123
-- UNPIVOT ID,another_field,price_number,price_value into CTE
;with upv as
(
-- UNPIVOT ID,price_value into CTE
select
ID,price_value
from
@table123
UNPIVOT
(
price_value
for price_number in ([Price1],[Price2],[Price3])
) pvt
),RNK as
(
-- Ranked table
select *,ROW_NUMBER() over (partition by ID order by price_value desc) as RN
from upv
)
select * from RNK where RN = 1
返回的结果是:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。