是否有一种简单的方法可以从(长)数组中进行选择? 我想要这样的东西
<img src="/path/to/image.php" />
但是我希望所有公民身份都作为列,而所有日期(从2000年到2018年)都作为行,因此我可以删除where子句。
答案 0 :(得分:0)
添加独特将为您提供唯一的公民列表
SELECT distinct citizenship
FROM table
WHERE year(date) >= 2000 and year(date) <= 2018
答案 1 :(得分:0)
想要使用PIVOT列的声音。
这里是我想要的...(在SQL Server中) 请参阅这篇文章:https://www.databasejournal.com/features/mssql/converting-rows-to-columns-pivot-and-columns-to-rows-unpivot-in-sql-server.html
可能会应用于您...
--Declare necessary variables
DECLARE @SQLQuery AS NVARCHAR(MAX)
DECLARE @PivotColumns AS NVARCHAR(MAX)
--Get unique values of pivot column
SELECT @PivotColumns= COALESCE(@PivotColumns + ',','') + QUOTENAME([citizenship])
FROM (SELECT DISTINCT [citizenship] FROM [dbo].[table]) AS PivotExample
--Create the dynamic query with all the values for
--pivot column at runtime
SET @SQLQuery =
N'SELECT [Year], ' + @PivotColumns + '
FROM (SELECT [citizenship], YEAR([Date]) AS [Year], COUNT(1) As Counter
FROM [Table] GROUP BY [citizenship], YEAR([Date])) AS A
PIVOT( SUM(Counter)
FOR [citizenship] IN (' + @PivotColumns + ')) AS P'
SELECT @SQLQuery
--Execute dynamic query
EXEC sp_executesql @SQLQuery