我是SAP v9.2(SQL Server 2008)的用户。我需要按日期获取名称和结果的数据并转换为1行,但是当我尝试使用此查询时:
SELECT
A.DATE,
SUM((ISNULL(A.HASIL_SHIFT1,0) AS HASIL_SHIFT1,
SUM((ISNULL(A.HASIL_SHIFT2,0) AS HASIL_SHIFT2,
SUM((ISNULL(A.HASIL_SHIFT3,0) AS HASIL_SHIFT3,
A.NAME
FROM
(SELECT
A.DATE,
CASE WHEN A.SHIFT=1 THEN A.HASIL END AS HASIL_SHIFT1,
CASE WHEN A.SHIFT=2 THEN A.HASIL END AS HASIL_SHIFT2,
CASE WHEN A.SHIFT=3 THEN A.HASIL END AS HASIL_SHIFT3,
A.NAME
FROM
(SELECT
A.DATE,
A.SHIFT
A.HASIL
B.NAME
FROM
(SELECT DISTINCT
DATE AS DATE,
SHIFT AS SHIFT,
QTY AS HASIL
FROM
TABLE T1
WHERE
DATE BETWEEN [%0] AND [%1]) A
LEFT JOIN
(SELECT DISTINCT
POSTING_DATE AS DATE
SHIFT AS SHIFT
NAMA AS NAME
FROM
TABLE T2) B ON A.DATE = B.DATE
AND A.SHIFT = B.SHIFT) A) A
我得到的结果如下:
DATE HASIL_SHIFT1 HASIL_SHIFT2 HASIL_SHIFT3 NAME
07.01.18 202.34 0.00 0.00 Arip Purnomo
07.01.18 0.00 217.86 0.00 Prayitno C Prayitno C
07.01.18 0.00 0.00 205.22
我可以获取列名称格式的数据可以像这样的数量总和相同:
DATE HASIL_SHIFT1 HASIL_SHIFT2 HASIL_SHIFT3 NAME_SHIFT1 NAME_SHIFT2 NAME_SHIFT3
07.01.18 202.34 217.86 205.22 Arip Purnomo Prayitno C Prayitno C
答案 0 :(得分:1)
尝试以下
SELECT
A.DATE,
ISNULL(SUM(CASE WHEN A.SHIFT=1 THEN A.HASIL END),0) AS HASIL_SHIFT1,
ISNULL(SUM(CASE WHEN A.SHIFT=2 THEN A.HASIL END),0) AS HASIL_SHIFT2,
ISNULL(SUM(CASE WHEN A.SHIFT=3 THEN A.HASIL END),0) AS HASIL_SHIFT3,
MAX(CASE WHEN A.SHIFT=1 THEN B.NAME END) AS NAME_SHIFT1,
MAX(CASE WHEN A.SHIFT=2 THEN B.NAME END) AS NAME_SHIFT2,
MAX(CASE WHEN A.SHIFT=3 THEN B.NAME END) AS NAME_SHIFT3
FROM
(
SELECT
DISTINCT
DATE AS DATE,
SHIFT AS SHIFT,
QTY AS HASIL
FROM
TABLE T1
WHERE
DATE BETWEEN [%0] AND [%1]
) A
LEFT JOIN
(
SELECT
DISTINCT
POSTING_DATE AS DATE,
SHIFT AS SHIFT,
NAMA AS NAME
FROM
TABLE T2
) B
ON
A.DATE=B.DATE
AND A.SHIFT=B.SHIFT
GROUP BY A.DATE