我有一个类似这样的查询:
;WITH t as
(
select 1 as RowNumber, 1 as ObjectID, 10 as [Col1], 20 as [Col2], 20 as [Col3], 20 as [Col4] UNION ALL
select 2 as RowNumber, 2 as ObjectID, 20 as [Col1], 30 as [Col2], 40 as [Col3], 50 as [Col4]
)
SELECT RowNumber, ObjectID,
(
SELECT MAX(Amount)
FROM (
SELECT [Col1] AS Amount
UNION ALL
SELECT [Col2]
UNION ALL
SELECT [Col3]
UNION ALL
SELECT [Col4]
) d
WHERE Amount > 0
)
FROM t
查询工作正常,但我想知道Max(金额)的来源。
所以在我的结果集中,除了(RowNumber,ObjectId,Amount)之外,我希望列的名称(Col1,Col2,Col3,Col4)为字符串。
有没有办法做到这一点?
修改 评论中的问题:如果两列具有相同的最大值,它可以是一列?是的,它可以是一个。任何列名都可以,只要我知道它可能来自哪里。
使用SQL Server 2008
答案 0 :(得分:5)
不要MAX:使用TOP避免聚合/ GROUP BY。
它还可以使用WITH TIES
处理重复项我不确定你所拥有的是伪代码还是子查询,但这应该做你想做的事
SELECT TOP 1 -- WITH TIES if needed
*
FROM
(
SELECT RowNumber, ObjectID, [Col1] AS Amount, 'Col1' AS ColName
FROM table
UNION ALL
SELECT RowNumber, ObjectID, [Col2], 'Col2' AS ColName
FROM table
UNION ALL
SELECT RowNumber, ObjectID, [Col3], 'Col3' AS ColName
FROM table
UNION ALL
SELECT RowNumber, ObjectID, [Col4], 'Col4' AS ColName
FROM table
) foo
WHERE Amount > 0
ORDER BY Amount DESC
您的主要问题是,无论您如何操作,都必须触摸表格4次,因为子查询只返回一个值。我也看不到ROW_NUMBER解决方案(但可能有一个......: - )
答案 1 :(得分:3)
这是未经测试的:但是要了解您的数据是什么,这可能会有所帮助。不是真正的生产代码质量:
SELECT RowNumber, ObjectID,
(
SELECT MAX(Amount)
FROM (
SELECT str([Col1]) + ", col1, " AS Amount
UNION ALL
SELECT str([Col2]) + ", col2"
UNION ALL
SELECT str([Col3]) + ", col3"
UNION ALL
SELECT str([Col4]) + ", col4"
)
WHERE Amount > 0
)
FROM table
str()是DBMS的“toString()”函数。 您的SQL看起来很奇怪,您使用的是什么DBMS?
答案 2 :(得分:2)
;WITH t1 as(
select 1 as RowNumber, 1 as ObjectID, 10 as [Col1], 20 as [Col2], 20 as [Col3], 20 as [Col4] UNION ALL
select 2 as RowNumber, 2 as ObjectID, 20 as [Col1], 30 as [Col2], 40 as [Col3], 50000045 as [Col4]
),
t2 as(
SELECT RowNumber, ObjectID,
(
SELECT TOP 1 CAST(C AS BINARY(4)) + CAST(Amount as BINARY(4))
FROM (
SELECT 'Col1' AS C, [Col1] AS Amount
UNION ALL
SELECT 'Col2' AS C, [Col2]
UNION ALL
SELECT 'Col3' AS C, [Col3]
UNION ALL
SELECT 'Col4' AS C, [Col4]
) d
WHERE Amount > 0
ORDER BY Amount desc
) AS Top1
FROM t1
)
SELECT RowNumber,
ObjectID,
CAST(Left(Top1, 4) AS CHAR(4)) AS Col,
CAST(SUBSTRING(Top1,5,4) AS INT) AS Amount
FROM t2
答案 3 :(得分:1)
您可以结合使用UNPIVOT和OUTER APPLY:
;WITH t as (
select 1 as RowNumber, 1 as ObjectID, 10 as [Col1], 20 as [Col2],
20 as [Col3], 20 as [Col4] UNION ALL
select 2 as RowNumber, 2 as ObjectID, 20 as [Col1], 30 as [Col2],
40 as [Col3], 50 as [Col4] )
SELECT
RowNumber,
ObjectID,
ColName,
ColAmount
FROM t
OUTER APPLY (
SELECT TOP 1
ColName,
ColAmount
FROM
(
SELECT
Col1,
Col2,
Col3,
Col4
) x
UNPIVOT (
ColAmount FOR ColName IN (Col1, Col2, Col3, Col4)
) y
WHERE ColAmount > 0
ORDER BY ColAmount DESC
) z
结果:
RowNumber ObjectID ColName ColAmount
----------- ----------- --------- -----------
1 1 Col2 20
2 2 Col4 50