从表中获取数据,使用行作为列

时间:2009-11-07 14:16:28

标签: sql sql-server tsql

我的表格中有以下数据。

alt text http://img26.imageshack.us/img26/3746/productfield.png

我想提取具有此标准的ProductId

FieldValue = 1.0 and FieldValue = 'Y' and FieldValue = 'N'

使用以下查询

无法做到这一点
select * from MyTable
WHERE (FieldId = 50 AND (FieldValue BETWEEN '1.0' AND '1.0')) 
AND (FieldId = 55 AND FieldValue = 'Y') 
AND (FieldId = 60 AND FieldValue = 'N') 

我无法使用这样的查询。这也是获取ProductId 103和104。

select * from MyTable
WHERE (FieldId = 50 AND (FieldValue BETWEEN '1.0' AND '1.0')) 
OR (FieldId = 55 AND FieldValue = 'Y') 
OR (FieldId = 60 AND FieldValue = 'N') 

alt text http://img690.imageshack.us/img690/16/productfieldresult.png

我事先并不知道ProductId。实际上我想使用FieldValue标准提取ProductId。我不能在我的where子句中使用ProductId,因为我不知道。只有我知道是fieldValue和FieldId。

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

select distinct t1.productid
from mytable t1
inner join mytable t2 on t1.productid = t2.productid
inner join mytable t3 on t2.productid = t3.productid
where t1.fieldvalue = '1.0' and t1.fieldid = 50
and t2.fieldvalue = 'Y' and t2.fieldid = 55
and t3.fieldvalue = 'N' and t3.fieldid = 60

答案 1 :(得分:0)

这个怎么样?

ProductId = 101和FieldValue IN('1.0','Y','N')

[编辑]

也许你可以使用像这样的子查询?

SELECT *
FROM MyTable
WHERE ProductId = 
-- SubQuery for searching ProductId based on FieldId and FieldValue
(SELECT TOP 1 ProductId
FROM MyTable
WHERE (FieldId = 50 AND (FieldValue BETWEEN '1.0' AND '1.0'))

答案 2 :(得分:0)

记录的FieldValue一次不能有两个值,这就是x=1 and x=2这样的条件永远不会成立的原因。

您希望在条件之间使用or

ProductId = 101 and (FieldValue = '1.0' or FieldValue = 'Y' and FieldValue = 'N')

编辑:
如果您必须找到具有FieldId和FieldValue值组合的ProductId,则必须进行一些加入:

select * from MyTable
where ProductId = (
  select ProductId
  from MyTable m
  inner join MyTable m2 on m2.ProductId = m.ProductId and m2.FieldId = 55 and FieldValue = 'Y'
  inner join MyTable m3 on m3.ProductId = m.ProductId and m3.FieldId = 60 and FieldValue = 'N'
  where FieldId = 50 and FieldValue = '1.0'
)

答案 3 :(得分:0)

我想你想要以下内容:

SELECT ProductId from myTable
 WHERE ProductId IN (SELECT ProductId FROM myTable WHERE FieldId = 50 AND FieldValue = '1.0')
   AND ProductId IN (SELECT ProductId FROM myTable WHERE FieldId = 55 AND FieldValue = 'Y') 
   AND ProductId IN (SELECT ProductId FROM myTable WHERE FieldId = 60 AND FieldValue = 'N')

(您可以将其中一个标准放在外部SELECT中,但我想这样更容易阅读。)