我试图在几个表中获得最大列值。例如在下面的片段(它不起作用)我正在尝试 从所有3个表A,B和C中的列名'tickvalue'获取MAX值。不确定如何获取该值。
tickvalue列的数据类型是时间戳。
select
c.somkey
,MAX(a.tickvalue, b.tickvalue, c.tickvalue) as tickvalue
from A as a
join B as b
on a.key = b.key
join C as c
on b.somekey = c.somkey
where a.key = '<some key>'
由于
答案 0 :(得分:3)
这不是MAX()
聚合函数在TSQL中的工作方式(参见此处:TSQL MAX())
MAX函数仅在单列中获得最大值。
要在此处实现您想要的功能,您必须将三个值放入一列中。这可以使用UNPIVOT
PIVOT/UNPIVOT
此代码段可能会帮助您。
CREATE TABLE #A (ID INT, tickvalue INT)
CREATE TABLE #B (ID INT, tickvalue INT)
CREATE TABLE #C (ID INT, tickvalue INT)
INSERT INTO #A VALUES (1,1)
INSERT INTO #A VALUES (2,4)
INSERT INTO #A VALUES (3,7)
INSERT INTO #A VALUES (4,2)
INSERT INTO #A VALUES (5,8)
INSERT INTO #B VALUES (1,8)
INSERT INTO #B VALUES (2,7)
INSERT INTO #B VALUES (3,2)
INSERT INTO #B VALUES (4,4)
INSERT INTO #B VALUES (5,1)
INSERT INTO #C VALUES (1,2)
INSERT INTO #C VALUES (2,1)
INSERT INTO #C VALUES (3,2)
INSERT INTO #C VALUES (4,15)
INSERT INTO #C VALUES (5,2)
SELECT ID, MAX(tickvalue)
FROM
(SELECT C.ID, A.tickvalue t1, B.tickvalue t2, C.tickvalue t3
FROM #A AS a
JOIN #B AS b ON a.ID = b.ID
JOIN #C AS c ON b.ID = c.ID) p
UNPIVOT (tickvalue FOR tsource IN (t1,t2,t3)) AS unpvt
GROUP BY ID
DROP TABLE #A
DROP TABLE #B
DROP TABLE #C
答案 1 :(得分:1)
答案 2 :(得分:1)
使用替代方案UNPIVOTE
SELECT c.ID,
CASE WHEN a.tickvalue >= b.tickvalue THEN
CASE WHEN a.tickvalue >= c.tickvalue THEN a.tickvalue ELSE c.tickvalue END
ELSE CASE WHEN b.tickvalue >= c.tickvalue THEN b.tickvalue ELSE c.tickvalue END END
FROM A a JOIN B b ON a.ID = b.ID
JOIN C c ON b.ID = c.ID