我是T-SQL的初学者,我陷入一个问题,即每天必须产生一行,并且该表包含以下列“ DATE”,“ PRICE”,“ CATEGORY 1”,“ CATEGORY 2” ”。输出必须创建列(“ CATEGORY 1”,“ CATEGORY 2”的组合)并显示价格。如果没有价格,则应显示null。以下是我需要产生的结果
TABLE
-----------------------------------------------
DATE | PRICE | CATEGORY 1 | CATEGORY 2
-----------------------------------------------
20171215 285 Books Non-Fiction
20171212 390 Gaming PlayStation 4
20171213 40 Antiques collectables
输出
DATE | Books- Non-Fiction | Gaming - PlayStation 4 | Antiques - collectables
20171212 NULL 390 NULL
20171213 NULL NULL 40
20171215 285 NULL NULL
有可能实现这一目标吗?
答案 0 :(得分:3)
您可以尝试使用条件汇总函数
CREATE TABLE T(
DATE INT,
PRICE INT,
[CATEGORY 1] VARCHAR(50),
[CATEGORY 2] VARCHAR(50)
);
INSERT INTO T VALUES (20171215,285,'Books','Non-Fiction');
INSERT INTO T VALUES (20171212,390,'Gaming','PlayStation 4');
INSERT INTO T VALUES (20171213,40 ,'Antiques','collectables');
查询1 :
SELECT DATE,
SUM(CASE WHEN [CATEGORY 1] = 'Books' and [CATEGORY 2] = 'Non-Fiction' THEN PRICE end) 'Books- Non-Fiction ',
SUM(CASE WHEN [CATEGORY 1] = 'Gaming' and [CATEGORY 2] = 'PlayStation 4' THEN PRICE end) 'Gaming - PlayStation 4',
SUM(CASE WHEN [CATEGORY 1] = 'Antiques' and [CATEGORY 2] = 'collectables' THEN PRICE end) 'Antiques - collectables'
FROM T
GROUP BY DATE
ORDER BY DATE
Results :
| DATE | Books- Non-Fiction | Gaming - PlayStation 4 | Antiques - collectables |
|----------|---------------------|------------------------|-------------------------|
| 20171212 | (null) | 390 | (null) |
| 20171213 | (null) | (null) | 40 |
| 20171215 | 285 | (null) | (null) |
答案 1 :(得分:2)
尝试一下:
SELECT DATE,
SUM(CASE WHEN [CATEGORY 1] = 'Books' and [CATEGORY 2] = 'Non-Fiction' THEN PRICE ELSE null end) 'Books- Non-Fiction',
SUM(CASE WHEN [CATEGORY 1] = 'Gaming' and [CATEGORY 2] = 'PlayStation 4' THEN PRICE ELSE null end) 'Gaming - PlayStation 4',
SUM(CASE WHEN [CATEGORY 1] = 'Antiques' and [CATEGORY 2] = 'collectables' THEN PRICE ELSE NULL end) 'Antiques - collectables'
FROM YOURTABLE
GROUP BY DATE
ORDER BY DATE