我可以将它们一起添加到一起工作,用户可以选择对国家1或2有效并且两者同时我需要这些一起工作 如果可能的话 当用户选择两者时我需要它来显示两个测量值
我无法创建一个新表,因此我基本上需要根据哪个国家/地区和单位价格基础来填充
,CASE
WHEN bd.Validforcountry = 1 and BD.UnitpriceBase = 1
THEN '100 ml'
WHEN bd.Validforcountry = 1 and BD.UnitpriceBase = 2
THEN '1 l'
WHEN bd.Validforcountry = 1 and BD.UnitpriceBase = 3
THEN '100 g'
WHEN bd.Validforcountry = 1 and BD.UnitpriceBase = 4
THEN '1 Kg'
WHEN bd.Validforcountry = 1 and BD.UnitpriceBase = 5
THEN '750 ml'
ELSE BD.UnitpriceBase
END AS 'Unit price Declaration'
,CASE
WHEN bd.Validforcountry = 2 and BD.UnitpriceBase = 1
THEN '100 ml'
WHEN bd.Validforcountry = 2 and BD.UnitpriceBase = 2
THEN '1 l'
WHEN bd.Validforcountry = 2 and BD.UnitpriceBase = 3
THEN '100 g'
WHEN bd.Validforcountry = 2 and BD.UnitpriceBase = 4
THEN '1 Kg'
WHEN bd.Validforcountry = 2 and BD.UnitpriceBase = 5
THEN '750 ml'
ELSE BD.UnitpriceBase
END AS 'Unit price Declaration'
答案 0 :(得分:1)
只需创建一个新表,而不是创建复杂的CASE WHEN
,这样就可以通过简单的JOIN选择正确的值。像这样:
CREATE TABLE UnitPriceDeclaration
(
Country int,
UnitPriceBase int,
UnitPriceDeclaration varchar(20),
PRIMARY KEY (Country, UnitPriceBase)
);
通过这种方式,您可以像这样编写查询(虚拟连接,我不了解您的其他表格):
SELECT t1.someField,
t2.someOtherField,
t1.UnitPriceBase,
t2.Country,
upd.UnitPriceDeclaration
FROM oneTable t1,
INNER JOIN anotherTable t2 ON ...
INNER JOIN UnitPriceDeclaration upd ON upd.Country = t2.Country AND upd.UnitPriceBase = t1.UnitPriceBase -- maybe LEFT JOIN
WHERE...
这使您可以保持灵活性并根据需要添加/更改任意数量的国家/地区,UPB或UPD,而无需更改数据以外的任何内容。像你一样使用CASE WHEN
,你必须在每次发生变化时(可能在多个地方)更改你的代码。
您的编辑主张此解决方案。看到所有那些重复的值?
所以,让我们说你要显示两个UPD,一个用于英国,一个用于IRE。你只需要做这样的事情:
SELECT t1.someField,
t2.someOtherField,
t1.UnitPriceBase,
t2.Country,
upduk.UnitPriceDeclaration as UPD_UK,
updire.UnitPriceDeclaration as UPD_IRE
FROM oneTable t1,
INNER JOIN UnitPriceDeclaration upduk ON upd.UnitPriceBase = t1.UnitPriceBase AND upd.Country = 1
INNER JOIN UnitPriceDeclaration updire ON upd.UnitPriceBase = t1.UnitPriceBase AND upd.Country = 2
WHERE...