具有多列的SQL COUNT

时间:2016-01-20 17:09:54

标签: sql-server tsql

我有一个调用Web服务的应用程序,我最多可以向该服务器传递5个ID并返回信息。

我创建了一个'审核' SQL表中的行,用于记录所有提交的信息。

ID可以按任意顺序提交,列是

DLN0,DLN1,DLN2,DLN3,DLN4。

我还有DateTime和Username Columns,我想要尝试和做的是COUNT在任意一天中任何一列中输入ID的次数,因为我不想要有人提交与服务相同的ID超过两次(在任何给定的列中)。

我想我可以通过UNION来做到这一点,但这会让它变得非常混乱,或者这是唯一的方法吗?

我已经取得了一些成功

from matplotlib import pyplot

我的表:

SELECT COUNT(MyTbl.DLN0) AS [Count], MyTbl.DLN0 AS [DLN], MyTbl.Username, CONVERT(VARCHAR(12),MyTbl.RequestDT,103) AS [DateTime] FROM 
(
SELECT DLN0, [RequestDT], Username FROM dbo.MyL_Audit_Log
UNION
SELECT DLN1, [RequestDT], Username FROM dbo.MyL_Audit_Log
UNION
SELECT DLN2, [RequestDT], Username FROM dbo.MyL_Audit_Log
UNION
SELECT DLN3, [RequestDT], Username FROM dbo.MyL_Audit_Log
UNION
SELECT DLN4, [RequestDT], Username FROM dbo.MyL_Audit_Log
) AS MyTbl
WHERE MyTbl.DLN0 <> ''
GROUP BY MyTbl.DLN0, MyTbl.Username, CONVERT(VARCHAR(12),MyTbl.RequestDT,103)

样本ID&#39;

XYZ43562MC4 ABC23214MC2 LKU23411PO3

干杯。

1 个答案:

答案 0 :(得分:1)

您的查询没问题,但您可能希望使用Union ALL而不是Union(UNION语句对结果集执行SELECT DISTINCT。):

SELECT COUNT(MyTbl.DLN0) AS [Count], MyTbl.DLN0 AS [DLN], MyTbl.Username, CONVERT(VARCHAR(12),MyTbl.RequestDT,103) AS [DateTime] FROM 
(
SELECT DLN0, [RequestDT], Username FROM dbo.MyL_Audit_Log
UNION ALL
SELECT DLN1, [RequestDT], Username FROM dbo.MyL_Audit_Log
UNION ALL
SELECT DLN2, [RequestDT], Username FROM dbo.MyL_Audit_Log
UNION ALL
SELECT DLN3, [RequestDT], Username FROM dbo.MyL_Audit_Log
UNION ALL
SELECT DLN4, [RequestDT], Username FROM dbo.MyL_Audit_Log
) AS MyTbl
WHERE MyTbl.DLN0 <> ''
GROUP BY MyTbl.DLN0, MyTbl.Username, CONVERT(VARCHAR(12),MyTbl.RequestDT,103)