我需要帮助格式化sql查询中的数据以创建图表。 这是下面的查询。
SELECT install_status, Date_appended , COUNT(serial_number)
FROM Asset_Base
Where (Date_appended = '2017-09-26' OR Date_appended = '2017-08-31' OR Date_appended = '2017-07-31')
AND (install_status= 'Installed'
OR (install_status= 'In Stock' AND u_install_sub_status = 'Available')
OR install_status= 'Missing')
Group By install_status , Date_appended
返回:
install_status Date_appended (No column name)
In Stock 2017-08-31 00:00:00.000 10981
Installed 2017-08-31 00:00:00.000 58764
Missing 2017-08-31 00:00:00.000 51661
In Stock 2017-09-26 00:00:00.000 10830
Installed 2017-09-26 00:00:00.000 59083
Missing 2017-09-26 00:00:00.000 51209
我有什么方法可以让数据看起来像这样吗?
Date_appended In Stock Installed Missing
2017-08-31 10981 58764 51661
2017-09-26 10830 59083 51209
谢谢!
答案 0 :(得分:0)
如果你只是希望每Date_appended
行只有一行:
...
GROUP BY appended;
如果您想要的列只计算serial_numbers
,install_status
为In Stock
,请使用以下内容:
SELECT
COUNT(CASE WHEN install_status = 'In Stock' THEN 1 END),
...
case
个表达式将每个非In Stock
行映射到null
(由于else null
的隐含case
子句。 count
通常会忽略null
个值(与大多数聚合函数一样)。
可以同样添加其他列。
在此处阅读有关此透视技术的更多信息:http://modern-sql.com/use-case/pivot
答案 1 :(得分:0)
我认为您可以使用枢轴。希望以下查询对您有所帮助:
SELECT * FROM (
select 'In Stock' as install_status, '2017-08-31' as Date_appended , 10981 as 'serial_number'
UNION ALL
select 'Installed' as install_status, '2017-08-31' as Date_appended , 58764 as 'serial_number'
UNION ALL
select 'Missing' as install_status, '2017-08-31' as Date_appended , 51661 as 'serial_number'
) AS A
PIVOT
(
MAX(serial_number)
For install_status in ([In Stock] ,[Installed],[Missing])
) PT
RESULT :
Date_appended In Stock Installed Missing
------------- ----------- ----------- -----------
2017-08-31 10981 58764 51661
(1 row(s) affected)
答案 2 :(得分:0)
您可以使用此查询。
SELECT * FROM
( SELECT install_status, serial_number , Date_appended FROM @Asset_Base
WHERE Date_appended IN ('2017-09-26', '2017-08-31', '2017-07-31')
AND (install_status IN ( 'Installed' , 'Missing')
OR (install_status= 'In Stock' AND u_install_sub_status = 'Available')) ) SRC
PIVOT ( COUNT(serial_number) FOR install_status IN ([In Stock], [Installed], [Missing])) PVT