选择在一个字段上具有值且在另一个上的两个值之间的行

时间:2019-01-15 23:43:18

标签: sql-server select

我无法进行SELECT并寻求帮助:)

我需要选择在一个字段上具有一个ID,在另一个字段上具有两个指定值的行,例如:

string Header = driver.FindElement(By.CssSelector("#gridComponent > div.k-grid-header > div > table > thead > tr")).Text;
        // Get rows strings
        foreach(string row in Header.Split('\r'))
        {
            DataRow dataRow = dt.NewRow();
        }
        string[] HeaderSplit = Header.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        // create DataTable
        foreach (string c in HeaderSplit)
        {           
            dt.Columns.Add(c);
        }     

        var table = driver.FindElement(By.CssSelector("#gridComponent"));

        //Get Row value
        foreach (var row in table.FindElements(By.TagName("tr")))
        {
            //Configure Number of Col and row
            int cellIndex = 0;
            string[] arr = new string[11];

            //Get Cell Data
            foreach (var cell in row.FindElements(By.TagName("td")))
            {
                Console.WriteLine(cell); 
                //Number of Col Data Load
                    if (cellIndex <= 10)
                    {
                        arr[cellIndex] = cell.Text;
                    }
                    else
                        continue;    

                cellIndex++;
            }
            dt.Rows.Add(arr);
        }

然后我想获取每个ID和COLOR,它们在SIZE中都有两个值(例如2XL和3XL),如下所示:

ID.......COLOR........SIZE
001......GREEN........M
001......GREEN........L
001......GREEN........XL
001......GREEN........2XL
001......GREEN........3XL
001......RED..........2XL
002......WHITE........XL
002......WHITE........2XL
002......WHITE........3XL

不应包含“ 001-RED-2XL”,因为同一ID和颜色行中没有“ 3XL”。

非常感谢!

甜蜜的问候:)

2 个答案:

答案 0 :(得分:1)

这可以通过使用两个相关的子查询作为EXISTS过滤条件来实现。

SELECT t.id, t.color, t.size
FROM mytable t
WHERE 
    t.size IN ('2XL', '3XL')
    AND EXISTS (SELECT 1 FROM mytable WHERE id = t.id AND color = t.color AND size = '2XL')
    AND EXISTS (SELECT 1 FROM mytable WHERE id = t.id AND color = t.color AND size = '3XL')

另一种解决方案是使用自联接:

SELECT t.id, t.color, t.size
FROM mytable t
INNER JOIN mytable t2 
    ON t2.id = t.id
    AND t2.color = t.color
    AND (
         ( t.size = '2XL' AND t2.size = '3XL' )
         OR ( t.size = '3XL' AND t2.size = '2XL' )
    )

答案 1 :(得分:1)

您可以通过以下方式使用存在的内容:

select t.* from tablename t where
exists (
  select 1 from tablename where
  id = t.id and color = t.color and 
  size in ('2XL', '3XL') and t.size in ('2XL', '3XL') and
  size <> t.size
)
order by t.id, t.color, t.size