我有一个表,包含一个名为 组件 的字段。数据为 -
date component
----------------------------
2012/12/11 PRP,PU1,P
2012/12/12 PRP
我想得到像这样的结果 -
date P_QTY
-----------------------
2012/12/11 1
我尝试查询 -
select date,count(date) as P_Qty
from MyTable
where component like '%P%'
group by date
但我得到了结果 -
date P_QTY
-----------------------
2012/12/11 1
2012/12/12 1
PRP
和P
之间存在歧义
那么,如何消除P
,PRP
和PU1
之间的含糊不清?
提前谢谢。
答案 0 :(得分:1)
首先,不建议在date和P_QTY之间存储一对多的关系。
要获得所需的结果,您的查询应为
SELECT date,count(date) as P_Qty
FROM MyTable
where
(
component = 'P' OR
component LIKE 'P,%' OR
component LIKE '%,P,%' OR
component LIKE '%,P'
)
GROUP BY date
答案 1 :(得分:1)
您只需要详细了解% (Wildcard - Character):
匹配零个或多个字符的任何字符串。此通配符可用作前缀或后缀。
这是你想要的:
select date,count(date) as P_Qty
from MyTable
where component like '%,P%'
group by date
答案 2 :(得分:0)
试试这个:
select date,count(date) as P_Qty
from MyTable
where ',' + component + ',' like '%,P,%'
group by date
答案 3 :(得分:0)
这就是你所追求的:
select date,count(date) as P_Qty
from MyTable
where component = 'P' OR CHARINDEX(',P,', component) > 0 OR
LEFT(component, 2) = 'P,' OR RIGHT(component,2) = ',P'
group by date
同样可以应用于其他值。只是不要忘记更改LEFT和RIGHT函数的整数值。您还可以引入一个应该进行测试的变量。在这种情况下,LEFT和RIGHT函数的整数值将是此变量的LEN()
答案 4 :(得分:0)
请尝试:
select date,count(date) as P_Qty
from MyTable
where REPLACE(',' + component + ',', ' ', '') like '%,P,%'
group by date
答案 5 :(得分:-1)
看起来你的桌子坏了。将它变成第一范式。当每行只有component
列中的一个组件时,您的查询就变得微不足道了。
答案 6 :(得分:-1)
SELECT DATE,COUNT(*) AS P_QTY
FROM MYTABLE
WHERE INSTR(COMPONENT,'PU1',1,1)>0
GROUP BY DATE