我希望我的标题有意义,这是我的表格样本。
我的表有一列用于唯一的产品条形码,4个日期列用于存储产品通过检验区域的日期和时间(其中4个),我删除了我的示例中的日期,所以只是假设它们'所有相同的日期。
Product | Time1 | Time2 | Time3 | Time4
---------------------------------------
A | 10:00 | 10:15 | 10:30 | 10:45
B | 10:05 | 10:25 | 10:35 | 10:50
C | 10:10 | 10:20 | 10:40 | 10:55
输出:
Inspect1 | Inspect2 | Inspect3 | Inspect4
-----------------------------------------
A A A A
B C B B
C B C C
在我的输出中,我想多次按不同的顺序选择产品(按Time1排序,按Time2排序等)
我使用case select多次选择产品,我如何下订单以便得到类似上面的例子。
SELECT
CASE WHEN time1 BETWEEN '10:00' AND '11:00' THEN product END AS inspect1,
CASE WHEN time2 BETWEEN '10:00' AND '11:00' THEN product END AS inspect2,
CASE WHEN time3 BETWEEN '10:00' AND '11:00' THEN product END AS inspect3,
CASE WHEN time4 BETWEEN '10:00' AND '11:00' THEN product END AS inspect4
FROM Table
答案 0 :(得分:1)
以下是使用ROW_NUMBER
的解决方案:
WITH CteUnion(Product, TimeNum, Value) AS(
SELECT Product, 'Time1', Time1 FROM YourTable UNION ALL
SELECT Product, 'Time2', Time2 FROM YourTable UNION ALL
SELECT Product, 'Time3', Time3 FROM YourTable UNION ALL
SELECT Product, 'Time4', Time4 FROM YourTable
),
CteRN AS(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY TimeNum ORDER BY Value)
FROM CteUnion
),
CteOrd AS(
SELECT *,
Ord = ROW_NUMBER() OVER(PARTITION BY RN ORDER BY Value)
FROM CteRN
)
SELECT
Inspect1 = MAX(CASE WHEN Ord = 1 THEN Product END),
Inspect2 = MAX(CASE WHEN Ord = 2 THEN Product END),
Inspect3 = MAX(CASE WHEN Ord = 3 THEN Product END),
Inspect4 = MAX(CASE WHEN Ord = 4 THEN Product END)
FROM CteOrd
GROUP BY RN
ORDER BY RN