使用SELECT作为列

时间:2016-11-16 02:36:19

标签: sql-server nested-queries

我正在使用此查询

SELECT
     fullname,
     (SELECT 
          count([ID]) FROM [SDT-DB].[dbo].[tbl_InfoBoard_UserLogs] 
          WHERE fullname = fullname AND user_did ='login') AS [Login],
     (SELECT 
          count([ID]) FROM [SDT-DB].[dbo].[tbl_InfoBoard_UserLogs] 
          WHERE fullname = fullname AND user_did ='message') AS [View Messageboard],
     (SELECT 
          count([ID]) FROM [SDT-DB].[dbo].[tbl_InfoBoard_UserLogs] 
          WHERE fullname = fullname AND user_did ='notification') AS [View Notification],
     count([ID]) AS Count
FROM [SDT-DB].[dbo].[tbl_InfoBoard_UserLogs]
GROUP BY fullname

它似乎返回了所有用户日志......

1 个答案:

答案 0 :(得分:2)

使用条件聚合:

SELECT fullname,
       SUM(CASE WHEN user_did = 'login' THEN 1 ELSE 0 END) AS [Login],
       SUM(CASE WHEN user_did = 'message' AS [View Messageboard],
       SUM(CASE WHEN user_did = 'notification' THEN 1 ELSE 0 END) AS [View Notification],
       count([ID]) AS Count
FROM [SDT-DB].[dbo].[tbl_InfoBoard_UserLogs]
GROUP BY fullname;

你的逻辑不起作用,因为你没有相关条款。您似乎打算拥有fullname = fullname,但只要fullname不是NULL,它就会评估为真。但是,上面的内容更简单。