SQL查询中的平表

时间:2015-10-25 16:07:15

标签: sql sql-server tsql

我有一个返回两行的查询:

X   Y
20  0.148698
30  0.576208

我还有一个具有以下签名的功能:

ALTER FUNCTION [dbo].[SomeFunc]
(
    @x1 float,
    @y1 float,
    @x2 float,
    @y2 float
)

在此函数中从此查询传递params的最简单方法是什么?现在我有一个查询,它声明了四个局部变量,然后我做了四个查询来填充所有这些变量,然后才将它们传递给我的函数。但似乎有一些更好的解决方案。例如,我正在寻找类似的东西:

WITH CTE AS (
   SELECT X1 = ..., Y1 = ..., X2 = ..., Y2 = ...
)
SELECT TOP 1 SomeFunc(X1, Y1, X2, Y2)
FROM CTE

这就是我将此问题称为Table flat

的原因

整个查询是:

DECLARE @value float = 24;

WITH CTE AS (
    SELECT X = CAST([name] AS float),
           Y = [rank]
    FROM [issdss].[dbo].[crit_scale]
    WHERE criteria_id = 128
),
CTE2 as (
    SELECT CTE.*, LeftDiff = IIF(X <= @value, @value - X, NULL), RightDiff = IIF(X >= @value, X - @value, NULL)
    FROM CTE
),
CTE3 as (
    SELECT X, Y
    FROM CTE2
    WHERE LeftDiff = (SELECT MIN(LeftDiff) FROM CTE2)
          OR RightDiff = (SELECT MIN(RightDiff) FROM CTE2)
),
-- Some magic here to get X1,Y1,X2,Y2

1 个答案:

答案 0 :(得分:1)

如果总共有2行,你可以使用row_number&amp ;;最大:

        List<testClass> a = new List<testClass>();
        List<testClass> b = new List<testClass>();
        a.Add(new testClass() { ID = 1 });
        a.Add(new testClass() { ID = 2 });
        a.Add(new testClass() { ID = 3 });
        a.Add(new testClass() { ID = 4 });
        a.Add(new testClass() { ID = 5 });

        b.Add(new testClass() { ID = 3 });
        b.Add(new testClass() { ID = 5 });
        a.Select<testClass, int>(x => x.ID);

        var items = a.ExceptBYProperty(b, u => u.ID);

SQL Fiddle

中的示例