查询两种不同的方案

时间:2014-07-30 12:03:36

标签: sql sql-server-2008

我需要编写一个能够满足以下要求的查询

1.) Need to get one row for the combination of "PrimaryID1" and "PrimaryID2", there are more than one field for this combination.
2.) There are two sub conditions here we need to take in to account.
    2.a) For fields with "FlagField = 1"
         In some combination of "PrimaryID1" and "PrimaryID2" we have "FlagField = 1" in this case  only that particular field needs to be taken
    2.b) For fields with "FlagField IS NULL"
         If "FlagField IS NULL" then the requirement is like we need to pull the record for min of "PrimaryID3"(its a diff. field)

以下是数据的外观

-----------------------------------------------------------------------------------------------
PrimaryID1       PrimaryID2       PrimaryID3       FlagField       DataField1       DataField2
-----------------------------------------------------------------------------------------------
PPID11             PPID21           1                  0             DF111            DF211
PPID11             PPID21           2                  1             DF112            DF212
PPID11             PPID21           3                  0             DF113            DF213

PPID12             PPID22           1                 NULL           DF121            DF221
PPID12             PPID22           2                 NULL           DF122            DF222
PPID12             PPID22           3                 NULL           DF123            DF223

示例结果

-----------------------------------------------------------------------------------------------
PrimaryID1       PrimaryID2       PrimaryID3       FlagField       DataField1       DataField2
-----------------------------------------------------------------------------------------------
PPID11             PPID21           2                  1             DF112            DF212

PPID12             PPID22           1                 NULL           DF121            DF221

1 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER标识具有最低PrimaryID3的行。在case语句中包含它将允许您“有条件地将它”与FlagField组合。然后,您只需要过滤表达式的结果。

WITH cte AS
(
    SELECT *, r = CASE WHEN FlagField IS NOT NULL THEN FlagField ELSE ROW_NUMBER() OVER(PARTITION BY PrimaryID1, PrimaryID2 ORDER BY CAST(REPLACE(PrimaryID3, 'PPID', '') AS INT)) END
    FROM tbl
)
SELECT *
FROM cte
WHERE r = 1