与SQL中的case语句条件相关的值

时间:2018-09-12 19:43:37

标签: sql sql-server tsql case

我有两个表: 项目和工作 我正在尝试从项目表中获取项目的单位重量。 作业表有两个项目代码列。项目1,项目2 我正在使用类似的东西。

  CASE 
      WHEN job.item2 
      LIKE '%cc%'
      THEN item.unitweight * job.qty
      ELSE job.qty
      END AS specific item

工作表

+-----+-------+-------+-----+
| job | Item1 | Item2 | qty |
+-----+-------+-------+-----+
|   1 | aa    | aaa   |   5 |
|   2 | bb    | cc    |   6 |
|   3 | cc    | bb    |   7 |
|   4 | aa    | ddd   |   8 |
+-----+-------+-------+-----+

项目表

+------+-------------+
| Item | Unit Weight |
+------+-------------+
| aa   |           5 |
| bb   |           6 |
| cc   |           7 |
| dd   |           8 |
+------+-------------+

我想让查询返回与Item2关联的42,但我的查询返回36

3 个答案:

答案 0 :(得分:2)

我猜你想要这样的东西吗?

SELECT j.job, j.Item1, j.Item2, j.qty
    , CASE
        WHEN j.Item2 = 'cc'  -- or do you want it to only have cc in it? then it would be LIKE '%cc%'
            THEN i2.unitweight * j.qty
        ELSE
            j.qty
      END
FROM Job j
    INNER JOIN Item i1 ON j.Item1 = i1.Item
    INNER JOIN Item i2 ON j.Item2 = i2.Item;

编辑:查看查询后,您可能希望将THEN ISNULL((item_mst.unit_weight * jobmatl_mst.matl_qty),0更改为THEN ISNULL((bitem.unit_weight * jobmatl_mst.matl_qty),0。看来您只是在乘以错误的单位权重?

答案 1 :(得分:1)

使用对您问题的最佳解释,我想到了这一点:

  approval_date:
    label: inline
    type: datetime_plain
    weight: 3
    region: content
    settings:
      timezone_override: ''
    third_party_settings: {  }

对于作业2,这给出了42的答案,对于作业3,这给出了49的答案。

答案 2 :(得分:0)

  

ccitem时,我试图从item2表中获取cc

您可以通过将item2左连到查询中来实现:

SELECT
  ...
  CASE 
      WHEN job.item2 
      LIKE '%cc%'
      THEN i2.unitweight * job.qty -- Use i2.unweight
      ELSE job.qty
      END AS specific item
FROM job
JOIN item on item.Item=job.Item1
LEFT OUTER JOIN item i2 on i2.Item=job.Item2 -- Add this join