开发者

SQL Column Populating

I want to know if it is possible to create ano开发者_Python百科ther column in a table that has data that I wish to populate in this new column? The new column is Flag2. Here is the table:

SQL Column Populating

what I want to do is, where item id is 30, I want the ITEM ID to only display 30 once and, populate the QC Unsupportted in Flag2? How do I do this?

I can only think of doing an inner join but this is not working.

This is what I have done in trying to do so:

SELECT 
    A.ITEMID, A.FLAG1, A.FLAG2 
FROM 
    #FLAGS as A
INNER JOIN 
    #FLAGS as B ON A.ITEMID = B.ITEMID
GROUP BY 
    a.ITEMID, a.FLAG1, A.FLAG2
ORDER BY 
    ITEMID


Assuming I understand what you are after, if the current FLAG1 values are distinct for any ITEMID and you only have at most two instances of the same ID, I think this should do what you want:

SELECT
    lft.ITEMID
  , lft.FLAG1
  , rght.FLAG1 FLAG2
FROM (
  SELECT
      t.ITEMID
    , t.FLAG1
  FROM (
    SELECT
        l.ITEMID
      , l.FLAG1
      , COUNT(l.ITEMID) i
    FROM #FLAGS l
      INNER JOIN #FLAGS r ON l.ITEMID = r.ITEMID
    WHERE r.FLAG1 <= l.FLAG1
    GROUP BY
        l.ITEMID
      , l.FLAG1) t
  WHERE t.i=1) lft
  LEFT OUTER JOIN (
  SELECT
      t.ITEMID
    , t.FLAG1
  FROM (
    SELECT
        l.ITEMID
      , l.FLAG1
      , COUNT(l.ITEMID) i
    FROM #FLAGS l
      INNER JOIN #FLAGS r ON l.ITEMID = r.ITEMID
    WHERE r.FLAG1 <= l.FLAG1
    GROUP BY
        l.ITEMID
      , l.FLAG1) t
WHERE t.i=2) rght ON lft.ITEMID = rght.ITEMID

-- Or better
SELECT
    lft.ITEMID
  , lft.FLAG1
  , rght.FLAG1 FLAG2
FROM (
  SELECT
      t.ITEMID
    , t.FLAG1
  FROM (
    SELECT
        l.ITEMID
      , l.FLAG1
      , ROW_NUMBER() OVER(PARTITION BY ITEMID ORDER BY FLAG1) as i
    FROM test l) t
  WHERE t.i=1) lft
  LEFT OUTER JOIN (
  SELECT
      t.ITEMID
    , t.FLAG1
  FROM (
    SELECT
        l.ITEMID
      , l.FLAG1
      , ROW_NUMBER() OVER(PARTITION BY ITEMID ORDER BY FLAG1) as i
    FROM test l) t
  WHERE t.i=2) rght ON lft.ITEMID = rght.ITEMID

If you have additional flag values for the same ID, a new outer join can be added to a new inline table (rght2, rght3, etc.) where i=3, 4, etc. and you are selecting rght2 AS FLAG3, rght3 AS FLAG4, etc.

Also note that the current values for FLAG1 will be distributed through FLAG1 and FLAG2 in alphabetical order. If you wanted to distribute them in reverse order you could replace <= with >=. If you had more than two flags that you wanted distributed in a specific order, you would have to create a separate table with a ranking value and join to that which would be doable but even uglier!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜