给出如下表格:
+---------+------+--------+-----------+--------------+
| Empcode | name | desig | joinmonth | releivemonth |
+---------+------+--------+-----------+--------------+
| 1. | A1. | D1. | Jan-18. | null |
| 2. | A2. | D2. | Jan-18. | May-18 |
| 3. | A3. | D3. | Jan-18. | null |
+---------+------+--------+-----------+--------------+
我想显示表格:
+---------------+--------+--------+--------+--------+--------+
| Remarks | jan-18 | feb-18 | mar-18 | apr-18 | may-18 |
+---------------+--------+--------+--------+--------+--------+
| Joinmonth | 3 | 0 | 0 | 0 | 0 |
| Releivedmonth | 0 | 0 | 0 | 0 | 1 |
+---------------+--------+--------+--------+--------+--------+
答案 0 :(得分:1)
您需要先取消透视,然后再重新透视:
select max(BMI), STDDEV(WEIGHT) FROM MEASUREMENTS where
MEASUREMENTS.patient_id='nick' AND
MEASUREMENTS.measure_date BETWEEN DATE_SUB("2013-12-30", INTERVAL 6 YEAR) AND "2013-12-30";
答案 1 :(得分:0)
这是扩展评论而不是答案,请接受我 在拒绝投票之前需要使用格式控制。
您似乎在注释中添加了查询,尽管语法并不完全正确。您经常使用标准括号()
而不是括号[]
,并且在结束IN()
时缺少右括号。我相信您的查询应如下所示:
SELECT
empname AS remarks
, [1-1-18]
, [1-2-18]
, [1-3-18]
, [1-4-18]
, [1-5-18]
FROM (
SELECT
empname
, joimonth
, releivedmonth
FROM emply
) AS s
PIVOT (
COUNT(releivedmonth)
FOR joinmonth IN ([1-1-18], [1-2-18], [1-3-18], [1-4-18], [1-5-18])
) piv
您不应尝试在评论中添加查询,而只需编辑问题即可。
在此查询中,您所引用的值看起来像 1-1-18 ,但是在数据样本中根本没有看起来像这样的值。 [joinmonth]和[releivedmonth]列是什么数据类型?
对于这些列中的文本数据,您遇到了严重的问题。例如,如果所有这些都不同:Jan-18.
,Jan 18
,Jan-18
,那么它们将不会按照您的需要对齐。像这样的数据变化将使这不可能。
CREATE TABLE emply(
Empcode NUMERIC(9,0)
,empname VARCHAR(6)
,desig VARCHAR(8)
,joinmonth varchar(30)
,releivemonth varchar(30)
);
INSERT INTO emply(Empcode,empname,desig,joinmonth,releivemonth) VALUES (1.,'A1.','D1.','Jan-18.',NULL);
INSERT INTO emply(Empcode,empname,desig,joinmonth,releivemonth) VALUES (2.,'A2.','D2.','Jan-18.','May 18');
INSERT INTO emply(Empcode,empname,desig,joinmonth,releivemonth) VALUES (3.,'A3.','D3.','Jan-18.',NULL);
SELECT
empname AS remarks
, [Jan-18.]
, [Feb-18.]
, [Mar-18.]
, [Apr-18.]
, [May-18.]
FROM (
SELECT
empname
, joinmonth
, releivemonth
FROM emply
) AS s
PIVOT (
COUNT(releivemonth)
FOR joinmonth IN ([Jan-18.], [Feb-18.], [Mar-18.], [Apr-18.], [May-18.])
) piv
但是,输出是:
+----+---------+---------+---------+---------+---------+---------+
| | remarks | Jan-18. | Feb-18. | Mar-18. | Apr-18. | May-18. |
+----+---------+---------+---------+---------+---------+---------+
| 1 | A1. | 0 | 0 | 0 | 0 | 0 |
| 2 | A2. | 1 | 0 | 0 | 0 | 0 |
| 3 | A3. | 0 | 0 | 0 | 0 | 0 |
+----+---------+---------+---------+---------+---------+---------+
COUNT(releivemonth)
只有一个非空值